将python中的不相等列表压缩到一个列表中,该列表不会删除正在压缩的较长列表中的任何元素

Dil*_*war 32 python data-structures

我有两个清单

a = [1,2,3]
b = [9,10]
Run Code Online (Sandbox Code Playgroud)

我想将这两个列表组合(zip)到一个列表c

c = [(1,9), (2,10), (3, )]
Run Code Online (Sandbox Code Playgroud)

Python中的标准库中是否有任何函数可以执行此操作?

ins*_*get 42

你寻求的是什么 itertools.izip_longest

在Python3.x中,你寻求 itertools.zip_longest

>>> a = [1,2,3]
>>> b = [9,10]
>>> for i in itertools.izip_longest(a,b): print i
... 
(1, 9)
(2, 10)
(3, None)
Run Code Online (Sandbox Code Playgroud)

编辑1:如果你真的想摆脱Nones,那么你可以尝试:

>>> for i in (filter(None, pair) for pair in itertools.izip_longest(a,b)): print i
(1, 9)
(2, 10)
(3,)
Run Code Online (Sandbox Code Playgroud)

编辑2:回应史蒂夫的评论:

filter(lambda p: p is not None, pair) for pair in itertools.izip_longest(a,b)
Run Code Online (Sandbox Code Playgroud)

  • 对Python 3.5+使用`itertools.zip_longest`. (10认同)

Ry-*_*Ry- 9

另一种方式是map:

a = [1, 2, 3]
b = [9, 10]
c = map(None, a, b)
Run Code Online (Sandbox Code Playgroud)

虽然那也会包含(3, None)而不是(3,).要做到这一点,这是一个有趣的路线:

c = (tuple(y for y in x if y is not None) for x in map(None, a, b))
Run Code Online (Sandbox Code Playgroud)

  • 在 Python 2.7 中运行良好,但在 3.5 中不运行。对于 3.5 使用 `itertools.zip_longest`。 (2认同)