這篇文章對我有幫助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]
在Python 2.x中,你可能會考慮itertools.izip(zip在Python 3.x中做同樣的事情)。 – 2009-12-17 02:08:50
@NicholasRiley:不在乎爲什麼? – User 2013-01-25 22:58:27
它使用較少的內存,可能會更快;它會創建一個迭代器而不是中間列表。 – 2013-01-25 23:02:34