简体   繁体   中英

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

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 :

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

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