cho*_*man 130 python iteration list
我有纬度列表和经度列表,需要迭代纬度和经度对.
是否更好:
A.假设列表长度相等:
for i in range(len(Latitudes)):
Lat,Long=(Latitudes[i],Longitudes[i])
Run Code Online (Sandbox Code Playgroud)B.或者:
for Lat,Long in [(x,y) for x in Latitudes for y in Longitudes]:
Run Code Online (Sandbox Code Playgroud)(注意B是不正确的.这给了我所有的对,相当于itertools.product()
)
关于每个的相对优点的任何想法,或者更多的pythonic?
Rob*_*let 249
这是pythonic你可以得到:
for lat, long in zip(Latitudes, Longitudes):
print lat, long
Run Code Online (Sandbox Code Playgroud)
sat*_*esh 47
另一种方法是使用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
Run Code Online (Sandbox Code Playgroud)
与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
Run Code Online (Sandbox Code Playgroud)
在相同数据上使用地图:
>>> for i,j in map(None,a,b):
... print i,j
...
1 4
2 5
3 6
9 None
Run Code Online (Sandbox Code Playgroud)
Wog*_*gan 21
很zip
高兴在这里看到很多爱的答案.
但是应该注意的是,如果你在3.0之前使用python版本,itertools
标准库中的模块包含一个izip
返回iterable 的函数,在这种情况下更合适(特别是如果你的latt/long列表很长) .
在python 3和更高版本中zip
表现得像izip
.
Jud*_*ill 15
如果您的纬度和经度列表很大且延迟加载:
from itertools import izip
for lat, lon in izip(latitudes, longitudes):
process(lat, lon)
Run Code Online (Sandbox Code Playgroud)
或者如果你想避免for循环
from itertools import izip, imap
out = imap(process, izip(latitudes, longitudes))
Run Code Online (Sandbox Code Playgroud)
同时迭代两个列表的元素称为压缩,python为它提供内置函数,这里记录.
>>> 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
Run Code Online (Sandbox Code Playgroud)
[例子来自pydocs]
在您的情况下,它将是简单的:
for (lat, lon) in zip(latitudes, longitudes):
... process lat and lon
Run Code Online (Sandbox Code Playgroud)
这篇文章帮助了我zip()
。我知道我晚了几年,但我仍然想做出贡献。这是在 Python 3 中。
注意:在python 2.x中,zip()
返回元组列表;在 Python 3.x 中,zip()
返回一个迭代器。
itertools.izip()
在 python 2.x 中 ==zip()
在 python 3.x 中
由于看起来您正在构建一个元组列表,因此以下代码是尝试完成您正在执行的操作的最 Pythonic 方式。
>>> lat = [1, 2, 3]
>>> long = [4, 5, 6]
>>> tuple_list = list(zip(lat, long))
>>> tuple_list
[(1, 4), (2, 5), (3, 6)]
Run Code Online (Sandbox Code Playgroud)
或者,如果您需要更复杂的操作,您可以使用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]
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
136659 次 |
最近记录: |