将两个元组中的交替值添加到空列表中(python3)

Mol*_*ly 2 python tuples list

给定元组:tuple1 = (3,5,16,35,75) 和 tuple2 = (1,19,28,44,64),我希望输出为 list5=[3, 1, 5, 19, 16、28、35、44、75、64]。这就是我所做的,但我知道这不是最好的方法。

list5 =[]
list5.append(tuple1[0])
list5.append(tuple2[0])
list5.append(tuple1[1])
list5.append(tuple2[1])
list5.append(tuple1[2])
list5.append(tuple1[3])
list5.append(tuple2[3])
list5.append(tuple1[4])
list5.append(tuple2[4])
print(list5)
Run Code Online (Sandbox Code Playgroud)

Cor*_*mer 6

然后,您可以zip使用列表理解将两个元组创建一个列表。

>>> tuple1 = (3,5,16,35,75)
>>> tuple2 = (1,19,28,44,64)
>>> [i for j in zip(tuple1, tuple2) for i in j]
[3, 1, 5, 19, 16, 28, 35, 44, 75, 64]
Run Code Online (Sandbox Code Playgroud)

如果元组的长度有可能不均匀,您可以itertools.zip_longest使用zip

>>> from itertools import zip_longest
>>> tuple1 = (3,5,16,35,75)
>>> tuple2 = (1,19,28,44,64,89,101)
>>> [i for j in zip_longest(tuple1, tuple2) for i in j if i is not None]
[3, 1, 5, 19, 16, 28, 35, 44, 75, 64, 89, 101]
Run Code Online (Sandbox Code Playgroud)