我有
a = [1, 2]
b = ['a', 'b']
我想要
c = [1, 'a', 2, 'b']
答案 0 :(得分:56)
[j for i in zip(a,b) for j in i]
答案 1 :(得分:25)
如果元素的顺序与示例中的顺序非常匹配,那么您可以使用zip和chain的组合:
from itertools import chain
c = list(chain(*zip(a,b)))
如果您不关心结果中元素的顺序,那么有一种更简单的方法:
c = a + b
答案 2 :(得分:22)
解析
[j for i in zip(a,b) for j in i]
如果您记得for
和if
条款是按顺序完成的,那么在您的脑海中很容易,最后追加结果:
temp = []
for i in zip(a, b):
for j in i:
temp.append(j)
如果用更有意义的变量名称编写它会更容易:
[item for pair in zip(a, b) for item in pair]
答案 3 :(得分:5)
使用索引切片的替代方法比zip更快且扩展性更好:
def slicezip(a, b):
result = [0]*(len(a)+len(b))
result[::2] = a
result[1::2] = b
return result
你会注意到这只适用于len(a) == len(b)
,但是设置模拟zip的条件不会随a或b缩放。
进行比较:
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
答案 4 :(得分:4)
如果您关心订单:
#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
提供[1, 'a', 2, 'b']
答案 5 :(得分:0)
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()的
答案 6 :(得分:0)
这是一个标准/自我解释的解决方案,我希望有人会发现它很有用:
a = ['a', 'b', 'c']
b = ['1', '2', '3']
c = []
for x, y in zip(a, b):
c.append(x)
c.append(y)
print (c)
输出:
['a', '1', 'b', '2', 'c', '3']
当然,如果需要,您可以更改它并对值进行操作
答案 7 :(得分:-2)
c = []
c.extend(a)
c.extend(b)