itertools.izip_longest()
接受一个fillvalue
论点。在 Python 3 上,它是itertools.zip_longest()
.
>>> l = [[1,2,3], [4,5], [], [6,7,8,9]]
>>> import itertools
>>> list(itertools.izip_longest(*l, fillvalue=""))
[(1, 4, '', 6), (2, 5, '', 7), (3, '', '', 8), ('', '', '', 9)]
如果您确实需要子列表而不是元组:
>>> [list(tup) for tup in itertools.izip_longest(*l, fillvalue="")]
[[1, 4, '', 6], [2, 5, '', 7], [3, '', '', 8], ['', '', '', 9]]
当然这也适用于字符串:
>>> l = [['a','b','c'], ['d','e'], [], ['f','g','h','i']]
>>> import itertools
>>> list(itertools.izip_longest(*l, fillvalue=""))
[('a', 'd', '', 'f'), ('b', 'e', '', 'g'), ('c', '', '', 'h'), ('', '', '', 'i')]
它甚至可以这样工作:
>>> l = ["abc", "de", "", "fghi"]
>>> list(itertools.izip_longest(*l, fillvalue=""))
[('a', 'd', '', 'f'), ('b', 'e', '', 'g'), ('c', '', '', 'h'), ('', '', '', 'i')]