简体   繁体   English

如何从python中的两个二维列表创建元组的二维列表?

[英]How to create 2-D lists of tuples from two 2-D lists in python?

I have two 2d lists, eg:我有两个二维列表,例如:

a = [[1, 2], [3, 4]]
b = [[5, 6], [7, 8]]

Then how can I get one 2d list of tuples: [[(1,5), (2,6)], [(3,7), (4,8)]]?那么我怎样才能得到一个二维元组列表:[[(1,5), (2,6)], [(3,7), (4,8)]]?

I see that you have answered your own question, as follows:我看到你已经回答了你自己的问题,如下:

[[(i1,j1) for i1, j1 in zip(i, j)] for i, j in zip(a, b)]

However, a simplified form exists, along similar lines but working directly with the tuples instead of unpacking them into multiple variables -- also the first list comprehension can be replaced by just calling list on the output of zip :然而,存在一种简化的形式,沿着类似的路线,但直接使用元组而不是将它们解包成多个变量——第一个列表理解也可以通过在zip的输出上调用list来替换:

[list(zip(*t)) for t in zip(a,b)]

or alternatively:或者:

vars = (a, b)
[list(zip(*t)) for t in zip(*vars)]

As well as being slightly simpler, this has the advantage that it is easier to generalise to more variables, for example if you had:除了稍微简单一点之外,这还有一个优点,即更容易推广到更多变量,例如,如果您有:

a = [[1, 2], [3, 4]]
b = [[5, 6], [7, 8]]
c = [[9, 10], [11, 12]]

Then you could do:那么你可以这样做:

vars = (a, b, c)

[list(zip(*t)) for t in zip(*vars)]

to give you:为你带来:

[[(1, 5, 9), (2, 6, 10)], [(3, 7, 11), (4, 8, 12)]]

我使用了这个代码:

data = [[(i1,j1) for i1, j1 in zip(i, j)] for i, j in zip(a, b)]

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

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