【发布时间】:2021-12-01 19:23:44
【问题描述】:
list1 = ["a", "b", "c"]
list2 = [1, 2, 3]
list3 = list1 + list2
print(list3)
output ---
['a', 'b', 'c', 1, 2, 3]
但我想要这样的输出 ---
['a',1,'b',2,'c',3]
请帮帮我
【问题讨论】:
list1 = ["a", "b", "c"]
list2 = [1, 2, 3]
list3 = list1 + list2
print(list3)
output ---
['a', 'b', 'c', 1, 2, 3]
但我想要这样的输出 ---
['a',1,'b',2,'c',3]
请帮帮我
【问题讨论】:
您可以创建一个for 循环并使用zip 和extend:
list1 = ["a", "b", "c"]
list2 = [1, 2, 3]
list3 = []
for items in zip(list1, list2):
list3.extend(items)
print(list3)
或者一个列表推导(但是它更慢且可读性较差,仍然将它保留在这里只是为了了解如何处理必须在推导中扩展可迭代的情况)
list1 = ["a", "b", "c"]
list2 = [1, 2, 3]
list3 = [c for items in zip(list1, list2) for c in items]
print(list3)
【讨论】:
for 循环更容易阅读,甚至可能更快。
.append 方法分辨率,这可以使用类似 append = result.append 的循环来完成
timeit 表明循环稍微快一点,我的想法是一样的,它不使用嵌套循环(也许在内部它使用了一些循环机制,但那是然后可能在 c) 中完成
from itertools import chain
list1 = ["a", "b", "c"]
list2 = [1, 2, 3]
result = list(chain(*zip(list1, list2)))
print(result)
正如@juanpa.arrivillaga 所述,作为[更好] 的替代方案(因为您传递给.from_iterable() 的参数将被延迟评估):
result = list(chain.from_iterable(zip(list1, list2)))
【讨论】:
chain.from_iterable
*zip()相比,使用它有什么好处吗?不过,我更新了我的答案。
chain.from_iterable 迭代 zip 对象本身,而不必将整个序列扩展到内存中以便将每个元素传递给 chain。
蛮力合并将是这样的:
list1 = ['a', 'b', 'c']
list2 = [1, 2, 3]
list3 = []
## merge two list with output like ['a',1,'b',2,'c',3]
for i in range(len(list1)):
list3.append(list1[i])
list3.append(list2[i])
print(list3)
更好的方法是使用上面的itertool或chain!
【讨论】:
for i in range(len(list1))