我有2个名单:
x = ['a','b','c']
y = ['d','e','f']
我需要一个列表清单:
z = [['a','d'],['b','e'],['c','f']]
我尝试了什么:
# Concatenate x and y with a space
w = []
for i in range(len(x)):
w.append(x[i]+" "+y[i])
# Split each concatenated element into a sublist
z = []
for i in range(len(w)):
z.append(w[i].split())
有没有办法在不使用2 for循环的情况下直接执行此操作? (我对Python很新)
答案 0 :(得分:5)
如果列表很大,您可以使用zip
(itertools.izip
):
>>> x = ['a','b','c']
>>> y = ['d','e','f']
>>> zip(x, y)
[('a', 'd'), ('b', 'e'), ('c', 'f')]
>>> map(list, zip(x, y)) # If you need lists instead of tuples
[['a', 'd'], ['b', 'e'], ['c', 'f']]
>>>
答案 1 :(得分:0)
如果两个长度相同,则使用enumerate
:
[[a,y[ind]] for ind, a in enumerate(x)]
它比zip
更有效。
In [6]: %timeit [[a,y[ind]] for ind,a in enumerate(x)]
1000000 loops, best of 3: 970 ns per loop
In [7]: %timeit map(list, zip(x, y))
1000000 loops, best of 3: 1.48 µs per loop