티스토리 뷰
Stack Overflow에 자주 검색, 등록되는 문제들과 제가 개발 중 찾아 본 문제들 중에서 나중에도 찾아 볼 것 같은 문제들을 정리하고 있습니다.
Stack Overflow에서 가장 먼저 확인하게 되는 가장 높은 점수를 받은 Solution과 현 시점에 도움이 될 수 있는 가장 최근에 업데이트(최소 점수 확보)된 Solution을 각각 정리하였습니다.
아래 word cloud를 통해 이번 포스팅의 주요 키워드를 미리 확인하세요.

How do I iterate through two lists in parallel?
두 개의 리스트를 병렬로 반복하려면 어떻게 해야 합니까?
문제 내용
I have two iterables, and I want to go over them in pairs:
두 개의 반복 가능한 자료가 있는데, 두 개씩 짝을 지어 검토하려고 합니다.
foo = [1, 2, 3]
bar = [4, 5, 6]
for (f, b) in iterate_together(foo, bar):
print("f:", f, " | b:", b)
That should result in:
결과는 다음과 같습니다.
f: 1 | b: 4
f: 2 | b: 5
f: 3 | b: 6
One way to do it is to iterate over the indices:
이를 수행하는 한 가지 방법은 다음과 같습니다.
for i in range(len(foo)):
print("f:", foo[i], " | b:", bar[i])
But that seems somewhat unpythonic to me. Is there a better way to do it?
하지만 그것은 파이썬스럽지가 않습니다. 더 좋은 방법이 없을까요?
높은 점수를 받은 Solution
Python 3
파이썬 3
for f, b in zip(foo, bar):
print(f, b)
zip stops when the shorter of foo or bar stops.
zip은 food 또는 bar 중 짧은 것이 멈추면 멈춘다.
In Python 3, zip returns an iterator of tuples, like itertools.izip in Python2. To get a list of tuples, use list(zip(foo, bar)). And to zip until both iterators are exhausted, you would use itertools.zip_longest.
Python 3에서 zip은 Python2의 itertools.izip과 같은 튜플의 반복자를 반환합니다. 튜플 리스트를 얻으려면 list(zip(foo, bar))를 사용하십시오. 그리고 두 반복자가 소진될 때까지 압축하려면 itertools.zip_longest를 사용합니다.
Python 2
파이썬 2
In Python 2, zip returns a list of tuples. This is fine when foo and bar are not massive. If they are both massive then forming zip(foo,bar) is an unnecessarily massive temporary variable, and should be replaced by itertools.izip or itertools.izip_longest, which returns an iterator instead of a list.
Python 2에서 zip은 튜플 목록을 반환합니다. foo와 bar가 크지 않을 때는 괜찮습니다. 둘 다 큰 경우 zip(foo,bar)를 형성하는 것은 불필요하게 큰 임시 변수이며 리스트 대신 반복자를 반환하는 itertools.izip 또는 itertools.izip_longest로 대체해야 합니다.
import itertools
for f,b in itertools.izip(foo,bar):
print(f,b)
for f,b in itertools.izip_longest(foo,bar):
print(f,b)
izip stops when either foo or bar is exhausted. izip_longest stops when both foo and bar are exhausted. When the shorter iterator(s) are exhausted, izip_longest yields a tuple with None in the position corresponding to that iterator. You can also set a different fillvalue besides None if you wish. See here for the full story.
foo 또는 bar 중 하나가 소진되면 izip이 중지됩니다. foo와 bar가 모두 소진되면 izip_messages가 중지됩니다. 짧은 반복기가 모두 사용되면 izip_longest는 해당 반복기에 해당하는 위치에 없음이 있는 튜플을 생성합니다. 원하는 경우 없음 외에 다른 채우기 값을 설정할 수도 있습니다. 자세한 내용은 여기를 참조하십시오.
Note also that zip and its zip-like brethen can accept an arbitrary number of iterables as arguments. For example,
또한 zip 및 zip과 유사한 brethen은 임의의 수의 반복 가능한 변수를 인수로 사용할 수 있습니다. 예를들면,
for num, cheese, color in zip([1,2,3], ['manchego', 'stilton', 'brie'],
['red', 'blue', 'green']):
print('{} {} {}'.format(num, color, cheese))
prints
출력
1 red manchego
2 blue stilton
3 green brie
가장 최근 달린 Solution
We can just use an index to iterate...
인덱스를 사용해서 반복하려면...
foo = ['a', 'b', 'c']
bar = [10, 20, 30]
for indx, itm in enumerate(foo):
print (foo[indx], bar[indx])
출처 : https://stackoverflow.com/questions/1663807/how-do-i-iterate-through-two-lists-in-parallel
'개발 > 파이썬' 카테고리의 다른 글
| collections.defaultdict() 활용법 (0) | 2022.12.12 |
|---|---|
| 파이썬2에서 dict.items()와 dict.iteritems()의 차이점 (0) | 2022.12.12 |
| Pandas 데이터프레임 CSV 파일로 내보내기 (0) | 2022.12.12 |
| 딕셔너리에서 값으로 키 가져오기 (0) | 2022.12.11 |
| 리스트 반대로 순회하기 (0) | 2022.12.11 |