Zip()
のように機能するが、結果のリストの長さが-ではなく最長入力の長さとなるように結果をパディングする組み込み関数はありますか最短入力?
>>> a=['a1']
>>> b=['b1','b2','b3']
>>> c=['c1','c2']
>>> Zip(a,b,c)
[('a1', 'b1', 'c1')]
>>> What command goes here?
[('a1', 'b1', 'c1'), (None, 'b2', 'c2'), (None, 'b3', None)]
Python 3では itertools.Zip_longest
>>> list(itertools.Zip_longest(a, b, c))
[('a1', 'b1', 'c1'), (None, 'b2', 'c2'), (None, 'b3', None)]
None
パラメーターを使用して、fillvalue
とは異なる値を埋め込むことができます。
>>> list(itertools.Zip_longest(a, b, c, fillvalue='foo'))
[('a1', 'b1', 'c1'), ('foo', 'b2', 'c2'), ('foo', 'b3', 'foo')]
Python 2を使用すると、 itertools.izip_longest
(Python 2.6+)、またはmap
とともにNone
を使用できます。少し知られている map
の機能 (ただしmap
はPython 3.xで変更されたため、これは= Python 2.x)。
>>> map(None, a, b, c)
[('a1', 'b1', 'c1'), (None, 'b2', 'c2'), (None, 'b3', None)]
Python 2.6xはitertools
モジュールの izip_longest
。
Python 3を使用 Zip_longest
代わりに(先頭のi
なし)。
>>> list(itertools.izip_longest(a, b, c))
[('a1', 'b1', 'c1'), (None, 'b2', 'c2'), (None, 'b3', None)]
non itertools Python 3ソリューション:
def Zip_longest(*lists):
def g(l):
for item in l:
yield item
while True:
yield None
gens = [g(l) for l in lists]
for _ in range(max(map(len, lists))):
yield Tuple(next(g) for g in gens)
non itertools My Python 2ソリューション:
if len(list1) < len(list2):
list1.extend([None] * (len(list2) - len(list1)))
else:
list2.extend([None] * (len(list1) - len(list2)))