开发者

Python: how do I merge lists to create a nested list [duplicate]

This question already has answers here: Closed 11 year开发者_StackOverflow中文版s ago.

Possible Duplicate:

Python - merge items of two lists into a list of tuples

How do I merge two lists in a nested way?

Eg:

list1 = a,b,c

list2 = d,e,f

I want the output to be:

[[a,d][b,e][c,f]]


Just zip them:

>>> l1 = ['a', 'b', 'c']
>>> l2 = ['d', 'e', 'f']
>>> zip(l1, l2)
[('a', 'd'), ('b', 'e'), ('c', 'f')]

If you need lists, not tuples, in the result:

>>> [list(l) for l in zip(l1, l2)]
[['a', 'd'], ['b', 'e'], ['c', 'f']]


Direct copy and paste from book:

The zip function

Sometimes it’s useful to combine two or more iterables before looping over them. The zip function will take the corresponding elements from one or more iterables and combine them into tuples until it reaches the end of the shortest iterable:

>>> x = [1, 2, 3, 4]
>>> y = ['a', 'b', 'c']
>>> z = zip(x, y)
>>> list(z)
[(1, 'a'), (2, 'b'), (3, 'c')]
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜