压缩大小不等的列表

新手上路,请多包涵

我有两个列表

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

我想将这两个列表合并(zip)为一个列表 c 这样

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

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

原文由 Dilawar 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 398
2 个回答

通常,您为此使用 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 s(或作为 fillvalue= 传递的任何值)填充较短的迭代。如果这不是你想要的,那么你可以使用 理解 来过滤掉 None s:

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

原文由 inspectorG4dget 发布,翻译遵循 CC BY-SA 4.0 许可协议

另一种方式是 map

 a = [1, 2, 3]
b = [9, 10]
c = map(None, a, b)

尽管那也将包含 (3, None) 而不是 (3,) 。为此,这里有一条有趣的台词:

 c = (tuple(y for y in x if y is not None) for x in map(None, a, b))

原文由 Ry- 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题