web-dev-qa-db-ja.com

Python:最長の長さにパディングするZipのような関数?

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)]
138
Mark Harrison

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)]
191
Nadia Alramli

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)]
79
SilentGhost

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)
3
dansalmo

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)))
2
Helton Wernik