반응형
    
    
    
  파이썬 : 가장 긴 길이로 채워지는 지퍼 같은 기능?
작동 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+)하거나 사용할 수 있습니다 map로 None. 약간 알려진 기능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
반응형
    
    
    
  'IT박스' 카테고리의 다른 글
| 파이썬 프로그램을 일시 정지하는 올바른 방법 (0) | 2020.06.18 | 
|---|---|
| 다운로드 할 수없고 $ GOPATH가 설정되지 않았습니다 (0) | 2020.06.18 | 
| 파이썬에서 람다로 정렬하는 방법 (0) | 2020.06.18 | 
| 파이썬의 주요 방법 이해하기 (0) | 2020.06.17 | 
| Javascript에서 iframe의 본문 내용을 얻는 방법은 무엇입니까? (0) | 2020.06.17 |