Merge Two Numpy Arrays Into A List Of Lists Of Tuples
I haven't been able to figure this out. Thanks for any help: Have: >>> x = np.array([[1,2],[5,6]]) >>> x array([[1, 2], [5, 6]]) >>> y = np.array(
Solution 1:
Try this:
x_z = map(tuple,x)
y_z = map(tuple,y)
[list(i) for i in zip(x_z, y_z)]
Output:
[[(1, 2), (3, 4)], [(5, 6), (7, 8)]]
Solution 2:
This is a fun problem. Here's what I came up with:
print([list(map(tuple, i)) for i in zip(x, y)])
# [[(1, 2), (3, 4)], [(5, 6), (7, 8)]]
Basically, zipping x and y gets you:
[(array([1, 2]), array([3, 4])), (array([5, 6]), array([7, 8])]
and so then you convert each element first into a list, and then a tuple
Solution 3:
x = list([[1,2],[5,6]])
y = list([[3,4],[7,8]])
x
[[1, 2], [5, 6]]
y
[[3, 4], [7, 8]]
z=list(zip(x,y))
z
[([1, 2], [3, 4]), ([5, 6], [7, 8])]
Solution 4:
If you want to run through the rows of each matrix, you can do this:
for (row1, row2) inzip(x,y):
yield [tuple(row1), tuple(row2)]
# [ (1,2) , (3,4) ]
This will give you a generator (if you wrap it in a function), but you want a list. So instead, wrap it in a comprehension:
[ [tuple(row1),tuple(row2)] for (row1, row2) in zip(x,y) ]
Solution 5:
IIUC
z=np.array([x,y])
[list(map(tuple,z[:,x]))for x in range(len(x))]
Out[223]: [[(1, 2), (3, 4)], [(5, 6), (7, 8)]]
Post a Comment for "Merge Two Numpy Arrays Into A List Of Lists Of Tuples"