Python: how do I merge lists to create a nested list [duplicate]
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')]
精彩评论