假设我有多个Python列表。在多个Python列表的元素之间插入元素的一种快速方法是什么?
# Have
list1 = [1, 2, 3]
list2 = [10, 11, 12]
list3 = [20, 21, 22]
# Expect
list_between = [1, 10, 20, 2, 11, 21, 3, 12, 22]发布于 2020-07-10 22:06:15
list_between = [i for l in list(zip(list1, list2, list3)) for i in l] 只需使用zip并使用列表理解按顺序打印元组列表中的元素。
list(zip(list1, list2, list3)) # returns [(1, 10, 20), (2, 11, 21), (3, 12, 22)]发布于 2020-07-10 22:13:54
用于任意插入的纯python解决方案
如果想要将listB中的元素插入到listA中的任意位置,可以使用list.insert(index, object_to_insert)方法。
如果您非常关心速度,您应该知道这可能不会很快,因为python列表是implemented as dynamic arrays,而不是链表。为了更快地插入,您可能希望实现自己的链表类型。
交替numpy解
如果您希望以示例所示的方式组合三个列表,则可以将它们插入到numpy数组中,并对该数组进行转置。
In [1]: import numpy as np
In [2]: listA = [1, 2, 3]
...: listB = [4, 5, 6]
...: listC = [7, 8, 9]
...:
...: arr = np.array([listA, listB, listC])
...: arr.T
Out[2]:
array([[1, 4, 7],
[2, 5, 8],
[3, 6, 9]])
In [3]: arr.T.flatten()
Out[3]: array([1, 4, 7, 2, 5, 8, 3, 6, 9])
In [4]: arr.T.flatten().tolist()
Out[4]: [1, 4, 7, 2, 5, 8, 3, 6, 9]发布于 2020-07-10 22:25:37
itertools.recipes中有roundrobin,它可以做你想做的事情:
from itertools import cycle, islice
def roundrobin(*iterables):
"roundrobin('ABC', 'D', 'EF') --> A D E B F C"
# Recipe credited to George Sakkis
num_active = len(iterables)
nexts = cycle(iter(it).__next__ for it in iterables)
while num_active:
try:
for next in nexts:
yield next()
except StopIteration:
# Remove the iterator we just exhausted from the cycle.
num_active -= 1
nexts = cycle(islice(nexts, num_active))
list1 = [1, 2, 3]
list2 = [10, 11, 12]
list3 = [20, 21, 22]
list_between = list(roundrobin(list1,list2,list3))
print(list_between)输出:
[1, 10, 20, 2, 11, 21, 3, 12, 22]请注意,它也适用于长度不同的参数(请参阅docstring)。
https://stackoverflow.com/questions/62836003
复制相似问题