[使用zip_longest加入2个列表,但使用None删除组

问题描述 投票:0回答:1

如何删除其中没有任何人的组? zip_longest是否还有另一种选择?

str1 = ['-', '+']
str2 = ['a','b','c']

list(itertools.zip_longest(str1, str2))

输出:

[('-','a'), ('+','b'), (None,'c')]

预期输出:

[[-a], [+b]]
python python-3.x itertools
1个回答
1
投票

zip_longest()可以替代常规内置zip(),它将截断为您作为参数提供的最短列表:

>>> str1 = ['-', '+']
>>> str2 = ['a','b','c']
>>> zipped = list(zip(str1, str2))
>>> print(zipped)
[('-', 'a'), ('+', 'b')]
>>> # the following more closely resembles your desired output
>>> condensed = [''.join(tup) for tup in zipped]
>>> print(condensed)
['-a', '+b']

请注意,您也可以给fillvalue赋予关键字参数itertools.zip_longest(),以使其填充None以外的内容:

>>> zipped_long = list(itertools.zip_longest(str1, str2, fillvalue='~'))
>>> print(zipped_long)
[('-', 'a'), ('+', 'b'), ('~', 'c')]
© www.soinside.com 2019 - 2024. All rights reserved.