简体   繁体   English

将两个numpy数组合并到元组列表的列表中

[英]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: 基本上,将x和y压缩会得到:

[(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 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 . 根据明确规定的要求,当然可以修改此解决方案以使其根据需要进行概括。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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