Programming

두 개의 목록을 반복하는 더 좋은 방법이 있습니까? 각 반복마다 각 목록에서 하나의 요소를 얻습니까?

procodes 2020. 6. 30. 21:50
반응형

두 개의 목록을 반복하는 더 좋은 방법이 있습니까? 각 반복마다 각 목록에서 하나의 요소를 얻습니까? [복제]


이 질문에는 이미 답변이 있습니다.

위도 및 경도 중 하나의 목록이 있으며 위도와 경도 쌍을 반복해야합니다.

다음이 더 낫습니다.

  • A. 목록의 길이가 같다고 가정하십시오.

    for i in range(len(Latitudes):
        Lat,Long=(Latitudes[i],Longitudes[i])
    
  • B. 또는 :

    for Lat,Long in [(x,y) for x in Latitudes for y in Longitudes]:
    

(B는 정확하지 않습니다. 이것은 나에게 모든 쌍을 제공합니다. itertools.product())

각각의 상대적인 장점에 대한 생각이 있습니까?


이것은 당신이 얻을 수있는만큼 pythonic입니다.

for lat, long in zip(Latitudes, Longitudes):
    print lat, long

이 작업을 수행하는 다른 방법은을 사용하는 것 map입니다.

>>> a
[1, 2, 3]
>>> b
[4, 5, 6]
>>> for i,j in map(None,a,b):
    ...   print i,j
    ...
1 4
2 5
3 6

zip과 비교하여 map을 사용할 때의 한 가지 차이점은 zip으로 새 목록
의 길이가 가장 짧은 목록의 길이와 동일하다는 것입니다. 예를 들면 다음과 같습니다.

>>> a
[1, 2, 3, 9]
>>> b
[4, 5, 6]
>>> for i,j in zip(a,b):
    ...   print i,j
    ...
1 4
2 5
3 6

동일한 데이터에서 맵 사용 :

>>> for i,j in map(None,a,b):
    ...   print i,j
    ...

    1 4
    2 5
    3 6
    9 None

zip여기에 대한 답변에서 많은 사랑을 보게되어 기쁩니다 .

그러나 3.0 이전의 Python 버전을 사용하는 itertools경우 표준 라이브러리 모듈에는 izipiterable을 반환하는 함수가 포함되어 있습니다. 이 경우 더 적합합니다 (특히 latt / longs 목록이 매우 긴 경우) .

파이썬 3 이상에서는 다음과 zip같이 동작 izip합니다.


위도 및 경도 목록이 크고 느리게로드되는 경우 :

from itertools import izip
for lat, lon in izip(latitudes, longitudes):
    process(lat, lon)

또는 for-loop를 피하려면

from itertools import izip, imap
out = imap(process, izip(latitudes, longitudes))

동시에 두리스트의 요소를 통해 반복 완봉라고도 파이썬은 문서화되어 그것을위한 기능 내장 제공되는 여기 .

>>> x = [1, 2, 3]
>>> y = [4, 5, 6]
>>> zipped = zip(x, y)
>>> zipped
[(1, 4), (2, 5), (3, 6)]
>>> x2, y2 = zip(*zipped)
>>> x == list(x2) and y == list(y2)
True

[파이 독에서 가져온 예]

귀하의 경우 간단하게 다음과 같습니다.

for (lat, lon) in zip(latitudes, longitudes):
    ... process lat and lon

for Lat,Long in zip(Latitudes, Longitudes):

This post helped me with zip(). I know I'm a few years late, but I still want to contribute. This is in Python 3.

Note: in python 2.x, zip() returns a list of tuples; in Python 3.x, zip() returns an iterator. itertools.izip() in python 2.x == zip() in python 3.x

Since it looks like you're building a list of tuples, the following code is the most pythonic way of trying to accomplish what you are doing.

>>> lat = [1, 2, 3]
>>> long = [4, 5, 6]
>>> tuple_list = list(zip(lat, long))
>>> tuple_list
[(1, 4), (2, 5), (3, 6)]

Or, alternatively, you can use list comprehensions (or list comps) should you need more complicated operations. List comprehensions also run about as fast as map(), give or take a few nanoseconds, and are becoming the new norm for what is considered Pythonic versus map().

>>> lat = [1, 2, 3]
>>> long = [4, 5, 6]
>>> tuple_list = [(x,y) for x,y in zip(lat, long)]
>>> tuple_list
[(1, 4), (2, 5), (3, 6)]
>>> added_tuples = [x+y for x,y in zip(lat, long)]
>>> added_tuples
[5, 7, 9]

참고URL : https://stackoverflow.com/questions/1919044/is-there-a-better-way-to-iterate-over-two-lists-getting-one-element-from-each-l

반응형