gpt4 book ai didi

python - 大小不等的压缩列表

转载 作者:IT老高 更新时间:2023-10-28 22:03:14 25 4
gpt4 key购买 nike

我有两个列表

a = [1,2,3]
b = [9,10]

我想将这两个列表合并(压缩)成一个列表 c 这样

c = [(1,9), (2,10), (3, )]

Python 的标准库中是否有任何函数可以做到这一点?

最佳答案

通常,您使用 itertools.zip_longest为此:

>>> import itertools
>>> a = [1, 2, 3]
>>> b = [9, 10]
>>> for i in itertools.zip_longest(a, b): print(i)
...
(1, 9)
(2, 10)
(3, None)

但是 zip_longestNone 填充较短的可迭代对象(或作为 fillvalue= 参数传递的任何值)。如果这不是您想要的,那么您可以使用 comprehension过滤掉 Nones:

>>> for i in (tuple(p for p in pair if p is not None) 
... for pair in itertools.zip_longest(a, b)):
... print(i)
...
(1, 9)
(2, 10)
(3,)

但请注意,如果任何一个可迭代对象具有 None 值,这也会将它们过滤掉。如果您不希望这样,请为 fillvalue= 定义您自己的对象并过滤它而不是 None:

sentinel = object()

def zip_longest_no_fill(a, b):
for i in itertools.zip_longest(a, b, fillvalue=sentinel):
yield tuple(x for x in i if x is not sentinel)

list(zip_longest_no_fill(a, b)) # [(1, 9), (2, 10), (3,)]

关于python - 大小不等的压缩列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11318977/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com