Skip to content

Instantly share code, notes, and snippets.

@dboyliao
Last active October 21, 2020 12:39
Show Gist options
  • Save dboyliao/ccb5970ccafd6d5c0420d39514cb0464 to your computer and use it in GitHub Desktop.
Save dboyliao/ccb5970ccafd6d5c0420d39514cb0464 to your computer and use it in GitHub Desktop.
Broadcasted tuple
#!/usr/bin/env python3
# https://gist.github.com/dboyliao/ccb5970ccafd6d5c0420d39514cb0464
from pprint import pprint
import numpy as np
class _Tuple:
def __init__(self, *values):
self.__values = values
def __repr__(self):
return repr(self.__values)
def __iter__(self):
return iter(self.__values)
def get_item(self, idx):
return self.__values[idx]
def np_tuplize(arr1, arr2):
brod = np.broadcast(arr1, arr2)
return np.array([_Tuple(a, b) for a, b in brod]).reshape(brod.shape)
if __name__ == "__main__":
arr1 = np.random.rand(2, 3)
arr2 = np.arange(3)
pprint(np_tuplize(arr1, arr2).tolist())
"""
[[(0.6207583611085942, 0), (0.132802157792566, 1), (0.7309655500748603, 2)],
[(0.9369520471394103, 0), (0.0009374602957433753, 1), (0.7166118810532366, 2)]]
"""
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment