프로그래밍 언어/Python
Python에서 목록을 균등 한 크기의 청크로 반복하는 방법
Rateye
2021. 8. 27. 16:13
728x90
반응형
질문 : 청크 단위로 목록을 반복하는 가장 "파이썬"방법은 무엇입니까?
한 번에 4 개의 정수로 작업해야하는 정수 목록을 입력으로받는 Python 스크립트가 있습니다. 불행히도 입력을 제어 할 수 없거나 4 개 요소 튜플 목록으로 전달했습니다. 현재 저는 다음과 같이 반복하고 있습니다.
for i in range(0, len(ints), 4):
# dummy op for example code
foo += ints[i] * ints[i + 1] + ints[i + 2] * ints[i + 3]
"C-think"와 비슷해 보이지만,이 상황을 처리하는 더 비단뱀적인 방법이 있다고 생각합니다. 목록은 반복 후 삭제되므로 보존 할 필요가 없습니다. 아마도 이와 같은 것이 더 좋을까요?
while ints:
foo += ints[0] * ints[1] + ints[2] * ints[3]
ints[0:4] = []
그래도 여전히 "느낌"이 좋지는 않습니다. :-/
관련 질문 : Python에서 목록을 균등 한 크기의 청크로 어떻게 분할합니까?
답변
Python itertools
문서 의 레시피 섹션에서 수정되었습니다.
from itertools import zip_longest
def grouper(iterable, n, fillvalue=None):
args = [iter(iterable)] * n
return zip_longest(*args, fillvalue=fillvalue)
예
grouper('ABCDEFG', 3, 'x') # --> 'ABC' 'DEF' 'Gxx'
참고 : Python 2에서는 izip_longest
대신 zip_longest
.
출처 : https://stackoverflow.com/questions/434287/what-is-the-most-pythonic-way-to-iterate-over-a-list-in-chunks
728x90
반응형