IT박스

파이썬 : 가장 긴 길이로 채워지는 지퍼 같은 기능?

itboxs 2020. 6. 18. 21:32
반응형

파이썬 : 가장 긴 길이로 채워지는 지퍼 같은 기능?


작동 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)]

파이썬 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')]

파이썬이 사용하면 중 하나를 사용할 수 있습니다 itertools.izip_longest(파이썬 2.6+)하거나 사용할 수 있습니다 mapNone. 약간 알려진 기능map 이지만 mapPython 3.x에서 변경되었으므로 Python 2.x에서만 작동합니다.

>>> map(None, a, b, c)
[('a1', 'b1', 'c1'), (None, 'b2', 'c2'), (None, 'b3', None)]

Python 2.6x의 경우 itertoolsmodule을 사용하십시오 izip_longest.

Python 3의 경우 zip_longest대신 선행 ( i)을 사용하십시오.

>>> list(itertools.izip_longest(a, b, c))
[('a1', 'b1', 'c1'), (None, 'b2', 'c2'), (None, 'b3', None)]

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)

itertools가 아닌 My Python 2 솔루션 :

if len(list1) < len(list2):
    list1.extend([None] * (len(list2) - len(list1)))
else:
    list2.extend([None] * (len(list1) - len(list2)))

참고 URL : https://stackoverflow.com/questions/1277278/python-zip-like-function-that-pads-to-longest-length

반응형