如何删除其中没有任何人的组? zip_longest是否还有另一种选择?
str1 = ['-', '+']
str2 = ['a','b','c']
list(itertools.zip_longest(str1, str2))
输出:
[('-','a'), ('+','b'), (None,'c')]
预期输出:
[[-a], [+b]]
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')]