我想在python中交错4个相同长度的列表。
我搜索了这个站点,只看到如何在python中交错2:Interleaving two lists in Python
能给出4个列表的建议吗?
我有这样的列表
l1 = ["a","b","c","d"]
l2 = [1,2,3,4]
l3 = ["w","x","y","z"]
l4 = [5,6,7,8]我想要这样的列表
l5 = ["a",1,"w",5,"b",2,"x",6,"c",3,"y",7,"d",4,"z",8]发布于 2018-06-12 11:40:41
来自itertools菜谱
itertool 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))
print(*roundrobin(*lists)) # a 1 w 5 b 2 x 6 c 3 y 7 d 4 z 8使用切片
或者,这里是一个完全依赖于切片的解决方案,但要求所有列表的长度相同。
l1 = ["a","b","c","d"]
l2 = [1,2,3,4]
l3 = ["w","x","y","z"]
l4 = [5,6,7,8]
lists = [l1, l2, l3, l4]
lst = [None for _ in range(sum(len(l) for l in lists))]
for i, l in enumerate(lists):
lst[i:len(lists)*len(l):len(lists)] = l
print(lst) # ['a', 1, 'w', 5, 'b', 2, 'x', 6, 'c', 3, 'y', 7, 'd', 4, 'z', 8]发布于 2018-06-12 11:37:09
只是为了多样性,numpy.dstack和flatten可以做同样的事情。
>>> import numpy as np
>>> l1 = ["a","b","c","d"]
>>> l2 = [1,2,3,4]
>>> l3 = ["w","x","y","z"]
>>> l4 = [5,6,7,8]
>>> np.dstack((np.array(l1),np.array(l2),np.array(l3),np.array(l4))).flatten()
array(['a', '1', 'w', '5', 'b', '2', 'x', '6', 'c', '3', 'y', '7', 'd',
'4', 'z', '8'],
dtype='|S21') 顺便说一句,你实际上不需要创建一个数组,简短的版本也可以
>>> np.dstack((l1,l2,l3,l4)).flatten()
array(['a', '1', 'w', '5', 'b', '2', 'x', '6', 'c', '3', 'y', '7', 'd',
'4', 'z', '8'],
dtype='|S21') 发布于 2018-06-12 19:33:30
使用zip和reduce
import functools, operator
>>> functools.reduce(operator.add, zip(l1,l2,l3,l4))
('a', 1, 'w', 5, 'b', 2, 'x', 6, 'c', 3, 'y', 7, 'd', 4, 'z', 8)https://stackoverflow.com/questions/50808757
复制相似问题