给定元组: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)
最佳答案
您可以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]
如果元组的长度可能不均匀,您可以使用 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]
关于python - 将两个元组的交替值添加到空列表 (python3),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69409660/