[英]How do I merge two lists into a single list?
I have我有
a = [1, 2]
b = ['a', 'b']
I want我想
c = [1, 'a', 2, 'b']
[j for i in zip(a,b) for j in i]
If the order of the elements much match the order in your example then you can use a combination of zip and chain :如果元素的顺序与您示例中的顺序非常匹配,那么您可以使用zip和chain的组合:
from itertools import chain
c = list(chain(*zip(a,b)))
If you don't care about the order of the elements in your result then there's a simpler way:如果您不关心结果中元素的顺序,那么有一种更简单的方法:
c = a + b
Parsing解析
[item for pair in zip(a, b) for item in pair]
in your head is easy enough if you recall that the for
and if
clauses are done in order, followed a final append of the result:如果您还记得
for
和if
子句是按顺序完成的,然后是结果的最后追加,那么在您的脑海中就很容易了:
temp = []
for pair in zip(a, b):
for item in pair :
temp.append(item )
An alternate method using index slicing which turns out to be faster and scales better than zip:另一种使用索引切片的方法比 zip 更快且扩展性更好:
def slicezip(a, b):
result = [0]*(len(a)+len(b))
result[::2] = a
result[1::2] = b
return result
You'll notice that this only works if len(a) == len(b)
but putting conditions to emulate zip will not scale with a or b.您会注意到这仅在
len(a) == len(b)
时有效,但设置模拟 zip 的条件不会随 a 或 b 缩放。
For comparison:为了比较:
a = range(100)
b = range(100)
%timeit [j for i in zip(a,b) for j in i]
100000 loops, best of 3: 15.4 µs per loop
%timeit list(chain(*zip(a,b)))
100000 loops, best of 3: 11.9 µs per loop
%timeit slicezip(a,b)
100000 loops, best of 3: 2.76 µs per loop
If you care about order:如果您关心订单:
#import operator
import itertools
a = [1,2]
b = ['a','b']
#c = list(reduce(operator.add,zip(a,b))) # slow.
c = list(itertools.chain.from_iterable(zip(a,b))) # better.
print c
gives [1, 'a', 2, 'b']
print c
给出[1, 'a', 2, 'b']
Simple.. please follow this pattern.简单.. 请遵循此模式。
x = [1 , 2 , 3]
y = ["a" , "b" , "c"]
z =list(zip(x,y))
print(z)
def main():
drinks = ["Johnnie Walker", "Jose Cuervo", "Jim Beam", "Jack Daniels,"]
booze = [1, 2, 3, 4, 5]
num_drinks = []
x = 0
for i in booze:
if x < len(drinks):
num_drinks.append(drinks[x])
num_drinks.append(booze[x])
x += 1
else:
print(num_drinks)
return
main()主要的()
Here is a standard / self-explaining solution, i hope someone will find it useful:这是一个标准/自我解释的解决方案,我希望有人会觉得它有用:
a = ['a', 'b', 'c']
b = ['1', '2', '3']
c = []
for x, y in zip(a, b):
c.append(x)
c.append(y)
print (c)
output:输出:
['a', '1', 'b', '2', 'c', '3']
Of course, you can change it and do manipulations on the values if needed当然,您可以更改它并根据需要对值进行操作
c = []
c.extend(a)
c.extend(b)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.