交错4列出相同长度的python

机场之*_*场之王 22 python arrays python-3.x

我想在python中交错4个相同长度的列表.

我搜索这个网站,只看到如何在python中交错2: 在Python中交换两个列表

可以为4个清单提供建议吗?

我有这样的名单

l1 = ["a","b","c","d"]
l2 = [1,2,3,4]
l3 = ["w","x","y","z"]
l4 = [5,6,7,8]
Run Code Online (Sandbox Code Playgroud)

我想要列表

l5 = ["a",1,"w",5,"b",2,"x",6,"c",3,"y",7,"d",4,"z",8]
Run Code Online (Sandbox Code Playgroud)

sha*_*678 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]
Run Code Online (Sandbox Code Playgroud)


Aus*_*tin 23

itertools.chain并且zip:

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))))
Run Code Online (Sandbox Code Playgroud)

或者@PatrickHaugh建议使用chain.from_iterable:

list(chain.from_iterable(zip(l1, l2, l3, l4)))
Run Code Online (Sandbox Code Playgroud)

  • 我可能会使用[`chain.from_iterable`](https://docs.python.org/3/library/itertools.html#itertools.chain.from_iterable) (9认同)

Oli*_*çon 9

来自itertools食谱

itertool食谱建议你采用一种解决方案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
Run Code Online (Sandbox Code Playgroud)

切片

或者,这里的解决方案仅依赖于切片,但要求所有列表的长度相等.

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]
Run Code Online (Sandbox Code Playgroud)


Zev*_*Zev 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'))
Run Code Online (Sandbox Code Playgroud)

['a',1,'w',5,'b',2,'x',6,'c',3,'y',7,'d',4,'z',8]


rth*_*rth 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') 
Run Code Online (Sandbox Code Playgroud)

顺便说一下,你实际上不需要制作一个阵列,短版本也可以

>>> 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')   
Run Code Online (Sandbox Code Playgroud)