2009-12-17 127 views
100

我有一個緯度列表和經度之一,需要迭代經緯度對。有沒有更好的方法來迭代兩個列表,每個迭代從每個列表中獲取一個元素?

是更好地:

  • 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是不正確的,這給了我所有的對,equi價格到itertools.product()

任何想法,每個的相對優點,或哪種更pythonic?

回答

197

這是Python的,你可以得到:

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

在Python 2.x中,你可能會考慮itertools.izip(zip在Python 3.x中做同樣的事情)。 – 2009-12-17 02:08:50

+2

@NicholasRiley:不在乎爲什麼? – User 2013-01-25 22:58:27

+5

它使用較少的內存,可能會更快;它會創建一個迭代器而不是中間列表。 – 2013-01-25 23:02:34

6

遍歷,同時被稱爲荏苒兩個列表的元素,Python提供了一個內置的功能吧,這是記錄here

>>> 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 

[例子是從pydocs採取]

你的情況,這將是簡單的:

for (lat, lon) in zip(latitudes, longitudes): 
    ... process lat and lon 
5
for Lat,Long in zip(Latitudes, Longitudes): 
20

很高興看到很多的愛在這裏的答案zip

然而,應該指出的是,如果你是3.0之前使用Python版本中,itertools模塊中的標準庫包含izip函數返回一個迭代,這是在這種情況下(特別是當更合適您的LATT列表/多頭很長)。

在python 3和更高版本zip表現得像izip

39

另一種方法是使用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 

一個區別是,與拉鍊的新列表的長度是
相同最短列表的長度。 例如:

>>> 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 
+0

是否可以這樣做:14,15,16? – BomberMan 2015-03-03 11:55:41

15

的情況下,您的緯度和經度列表很大,延遲加載:

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

,或者如果你想避免for for循環

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

這篇文章對我有幫助zip()。我知道我遲了幾年,但我仍然想要貢獻。這是在Python 3中。

注意:在python 2.x中,zip()返回元組列表;在Python 3.x中,zip()返回一個迭代器。 itertools.izip()在蟒蟒3.x的2.x的== zip()

因爲它看起來像你正在構建一個元組列表,下面的代碼是想完成自己在做什麼是最Python的方式。

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

,或者,你可以使用list comprehensions(或list comps),你應該需要更多複雜的操作。列表解析的運行速度大約爲map(),花費或花費幾納秒,並正在成爲Pythonic與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] 
相關問題