在Python中交织多个相同长度的列表


85

在Python中,有没有一种好的方法来交错两个相同长度的列表?

说我被给[1,2,3][10,20,30]。我想把它们变成[1,10,2,20,3,30]


不推荐使用,但请尝试以下操作:it = iter(l1); list((yield next(it)) or i for i in l2)
Chris_Rands

Answers:


112

发布问题后,我意识到我可以简单地执行以下操作:

[val for pair in zip(l1, l2) for val in pair]

这两个列表在哪里l1l2


如果有N个列表要交织,则

lists = [l1, l2, ...]
[val for tup in zip(*lists) for val in tup]

5
仅当l1和l2具有相同数量的元素时才有效
Emmanuel

14
@Emmanuel:问题显示为“在Python中,有没有一种好的方法来插入两个相同长度的列表?”
NPE

1
如果您想垫最长的列表中,使用izip_longest了python2和zip_longest为python3`[val for pair in itertools.zip_longest(l1, l2) for val in pair]结果与['a', 'b', 'a', 'b', 'a', 'b', None, 'b', None, 'b', None, 'b']
谢尔盖·扎哈罗夫

71

对于Python> = 2.3,有扩展的slice语法

>>> a = [0, 2, 4, 6, 8]
>>> b = [1, 3, 5, 7, 9]
>>> c = a + b
>>> c[::2] = a
>>> c[1::2] = b
>>> c
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

该行c = a + b用作创建长度正确的新列表的简单方法(在此阶段,其内容并不重要)。接下来的两行完成交织的实际工作,a并且b:第一行将的元素分配给的a所有偶数索引c;第二个将的元素分配给的b所有奇数索引c


25

给定

a = [1, 2, 3]
b = [10, 20, 30]
c = [100, 200, 300, 999]

假设列表的长度相等,则可以使用itertools.chain和获得交错列表zip

import itertools


list(itertools.chain(*zip(a, b)))
# [1, 10, 2, 20, 3, 30]

备择方案

itertools.zip_longest

更一般地,对于不相等的列表,请使用zip_longest(推荐):

[x for x in itertools.chain(*itertools.zip_longest(a, c)) if x is not None]
# [1, 100, 2, 200, 3, 300, 999]

可以安全地交错许多列表:

[x for x in itertools.chain(*itertools.zip_longest(a, b, c)) if x is not None]
# [1, 10, 100, 2, 20, 200, 3, 30, 300, 999]

more_itertools+

附带roundrobinitertools配方interleave和的库interleave_longest

import more_itertools


list(more_itertools.roundrobin(a, b))
# [1, 10, 2, 20, 3, 30]

list(more_itertools.interleave(a, b))
# [1, 10, 2, 20, 3, 30]

list(more_itertools.interleave_longest(a, c))
# [1, 100, 2, 200, 3, 300, 999]

yield from

最后,对于Python 3中的一些有趣的东西(尽管不推荐):

list(filter(None, ((yield from x) for x in zip(a, b))))
# [1, 10, 2, 20, 3, 30]

list([(yield from x) for x in zip(a, b)])
# [1, 10, 2, 20, 3, 30]

+使用安装pip install more_itertools


8

我需要一种方法来处理不同大小的列表,但接受的答案无法解决。

我的解决方案使用生成器,由于它的使用,它的用法看起来更好一些:

def interleave(l1, l2):
    iter1 = iter(l1)
    iter2 = iter(l2)
    while True:
        try:
            if iter1 is not None:
                yield next(iter1)
        except StopIteration:
            iter1 = None
        try:
            if iter2 is not None:
                yield next(iter2)
        except StopIteration:
            iter2 = None
        if iter1 is None and iter2 is None:
            raise StopIteration()

及其用法:

>>> a = [1, 2, 3, 4, 5]
>>> b = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
>>> list(interleave(a, b))
[1, 'a', 2, 'b', 3, 'c', 4, 'd', 5, 'e', 'f', 'g']
>>> list(interleave(b, a))
['a', 1, 'b', 2, 'c', 3, 'd', 4, 'e', 5, 'f', 'g']

该模块中的roundrobin配方itertools是对此的更一般的扩展。
ShadowRanger

7

选择:

>>> l1=[1,2,3]
>>> l2=[10,20,30]
>>> [y for x in map(None,l1,l2) for y in x if y is not None]
[1, 10, 2, 20, 3, 30]

这是可行的,因为地图可以并行处理列表。它在2.2下的工作原理相同None作为调用函数,它本身map会生成一个元组列表:

>>> map(None,l1,l2,'abcd')
[(1, 10, 'a'), (2, 20, 'b'), (3, 30, 'c'), (None, None, 'd')]

然后只需将元组列表弄平。

当然,优点是map 适用于任意数量的列表,即使长度不同也可以使用:

>>> l1=[1,2,3]
>>> l2=[10,20,30]
>>> l3=[101,102,103,104]
>>> [y for x in map(None,l1,l2,l3) for y in x if y in not None]
[1, 10, 101, 2, 20, 102, 3, 30, 103, 104]

1
if y也会过滤掉0if y is not None不那么脆弱。
Jochen Ritzel 2011年

@Jochen Ritzel:谢谢!我同意你的看法。固定。我写的时候只有肌肉……
狼,

3

我最喜欢aix的解决方案。这是我认为应该在2.2中工作的另一种方式:

>>> x=range(3)
>>> x
[0, 1, 2]
>>> y=range(7,10)
>>> y
[7, 8, 9]
>>> sum(zip(x,y),[])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: can only concatenate list (not "tuple") to list
>>> sum(map(list,zip(x,y)),[])
[0, 7, 1, 8, 2, 9]

还有另一种方法:

>>> a=[x,y]
>>> [a[i][j] for j in range(3) for i in (0,1)]
[0, 7, 1, 8, 2, 9]

和:

>>> sum((list(i) for i in zip(x,y)),[])
[0, 7, 1, 8, 2, 9]

0
[el for el in itertools.chain(*itertools.izip_longest([1,2,3], [4,5])) if el is not None]

只要没有None,就想保留


0

要回答“在Python中交织相同长度的多个列表”的问题标题,我们可以概括@ekhumoro的2列表答案。这明确要求列表长度相同,这与@NPE的(优雅)解决方案不同

import itertools

def interleave(lists):
    """Interleave a list of lists.

    :param lists: List of lists; each inner length must be the same length.
    :returns: interleaved single list
    :rtype: list

    """
    if len(set(len(_) for _ in lists)) > 1:
        raise ValueError("Lists are not all the same length!")
    joint = list(itertools.chain(*lists))
    for l_idx, li in enumerate(lists):
        joint[l_idx::len(lists)] = li
    return joint

例子:

>>> interleave([[0,2,4], [1, 3, 5]])
[0, 1, 2, 3, 4, 5]
>>> interleave([[0,2,4], [1, 3, 5], [10, 11, 12]])
[0, 1, 10, 2, 3, 11, 4, 5, 12]
>>> interleave([[0,2,4], [1, 3, 5], [10, 11, 12], [13, 14, 15]])
[0, 1, 10, 13, 2, 3, 11, 14, 4, 5, 12, 15]
>>> interleave([[0,2,4], [1, 3, 5], [10, 11, 12], [13, 14]])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 10, in interleave
ValueError: Lists are not all the same length!
>>> interleave([[0,2,4]])
[0, 2, 4]

0

参加聚会太晚了,有很多好的答案,但是我也想使用extend()方法提供一个简单的解决方案:

list1 = [1, 2, 3]
list2 = [10, 20, 30]

new_list = []
for i in range(len(list1)):
    new_list.extend([list1[i], list2[i]])
print(new_list)

输出:

[1, 10, 2, 20, 3, 30]
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.