交织4个相同长度的python列表

2024-10-08 19:19:51 发布

您现在位置:Python中文网/ 问答频道 /正文

我想在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]

我要单子

^{pr2}$

Tags: inl1列表站点建议lists单子two
3条回答

从itertools recipes

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

有切片吗

或者,这里有一个完全依赖切片的解决方案,但是要求所有列表的长度相等。在

^{pr2}$

^{}^{}

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建议使用^{}

^{pr2}$

如果列表的长度相同,^{}可用于交错四个列表,就像在您链接的问题中用于交错两个列表一样:

>>> 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]

相关问题 更多 >

    热门问题