大小不等的压缩列表 [英] Zipping lists of unequal size

查看:48
本文介绍了大小不等的压缩列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个列表

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

我想将这两个列表合并(压缩)为一个列表 c 使得

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

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

解决方案

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

<预><代码>>>>导入迭代工具>>>a = [1, 2, 3]>>>b = [9, 10]>>>对于 itertools.zip_longest(a, b) 中的 i:print(i)...(1, 9)(2, 10)(3, 无)

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

<预><代码>>>>for i in (tuple(p for p in pair if p is not None)...对于 itertools.zip_longest(a, b)) 中的对:...打印(一)...(1, 9)(2, 10)(3,)

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

sentinel = object()def zip_longest_no_fill(a, b):对于 i 在 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,)]

I have two lists

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

I want to combine (zip) these two lists into one list c such that

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

Is there any function in standard library in Python to do this?

解决方案

Normally, you use itertools.zip_longest for this:

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

But zip_longest pads the shorter iterable with Nones (or whatever value you pass as the fillvalue= parameter). If that's not what you want then you can use a comprehension to filter out the 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,)

but note that if either of the iterables has None values, this will filter them out too. If you don't want that, define your own object for fillvalue= and filter that instead of 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,)]

这篇关于大小不等的压缩列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆