简体   繁体   中英

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([[3,4],[7,8]])
>>> y
array([[3, 4],
       [7, 8]])

Want:

>>> z = [[(1,2),(3,4)],[(5,6),(7,8)]]
>>> z
[[(1, 2), (3, 4)], [(5, 6), (7, 8)]]

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)]]

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

If you want to run through the rows of each matrix, you can do this:

for (row1, row2) in zip(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) ]
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])]

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)]]

For what it's worth, here's the simplest and most efficient (but probably the least generalized) solution:

result = [[(x[0,0], x[0,1]), (y[0,0], y[0,1])],
         [(x[1,0], x[1,1]), (y[1,0], y[1,1])]]

Output:

[[(1, 2), (3, 4)], [(5, 6), (7, 8)]]

Admittedly, it doesn't generalize, but the question is -- in which direction is generalization required? Longer outer dimension? Longer inner dimension? The question hasn't called for any generalization.

Based on explicitly stated requirement, this solution can of course be modified to make it generalized just as much as needed .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM