我想在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]
答案 0 :(得分:28)
如果列表的长度相同,zip()
可用于交换四个列表,就像它在您链接的问题中用于交错两个列表一样:
>>> l1 = ["a", "b", "c", "d"]
>>> l2 = [1, 2, 3, 4]
>>> l3 = ["w", "x", "y", "z"]
>>> l4 = [5, 6, 7, 8]
>>> l5 = [x for y in zip(l1, l2, l3, l4) for x in y]
>>> l5
['a', 1, 'w', 5, 'b', 2, 'x', 6, 'c', 3, 'y', 7, 'd', 4, 'z', 8]
答案 1 :(得分:23)
from itertools import chain
l1 = ["a", "b", "c", "d"]
l2 = [1, 2, 3, 4]
l3 = ["w", "x", "y", "z"]
l4 = [5, 6, 7, 8]
print(list(chain(*zip(l1, l2, l3, l4))))
或者@PatrickHaugh建议使用chain.from_iterable
:
list(chain.from_iterable(zip(l1, l2, l3, l4)))
答案 2 :(得分:9)
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]
答案 3 :(得分:6)
有关其他多样性(或者如果您需要使用Pandas进行此操作)
import pandas as pd
l1 = ["a","b","c","d"]
l2 = [1,2,3,4]
l3 = ["w","x","y","z"]
l4 = [5,6,7,8]
df = pd.DataFrame([l1 ,l2, l3, l4])
result = list(df.values.flatten('A'))
['a',1,'w',5,'b',2,'x',6,'c',3,'y',7,'d',4,'z', 8]
答案 4 :(得分:5)
只是为了多样性,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')
答案 5 :(得分:4)
另一种方法可能是zip
使用np.concatenate
:
import numpy as np
l5 = np.concatenate(list(zip(l1, l2, l3, l4)))
print(l5)
结果:
['a' '1' 'w' '5' 'b' '2' 'x' '6' 'c' '3' 'y' '7' 'd' '4' 'z' '8']
注意:l5
是numpy.ndarray
类型,您可以使用list
或list(l5)
将其转换为l5.tolist()
答案 6 :(得分:2)
使用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)