問題描述
給定一個(gè)列表
l = [1, 7, 3, 5]
我想遍歷所有成對(duì)的連續(xù)列表項(xiàng)(1,7), (7,3), (3,5)
,即
I want to iterate over all pairs of consecutive list items (1,7), (7,3), (3,5)
, i.e.
for i in xrange(len(l) - 1):
x = l[i]
y = l[i + 1]
# do something
我想以更緊湊的方式來做這件事,比如
I would like to do this in a more compact way, like
for x, y in someiterator(l): ...
有沒有辦法使用內(nèi)置的 Python 迭代器來做到這一點(diǎn)?我確定 itertools
模塊應(yīng)該有解決方案,但我就是想不通.
Is there a way to do do this using builtin Python iterators? I'm sure the itertools
module should have a solution, but I just can't figure it out.
推薦答案
只要使用 拉鏈
>>> l = [1, 7, 3, 5]
>>> for first, second in zip(l, l[1:]):
... print first, second
...
1 7
7 3
3 5
如果您使用 Python 2(不建議),您可能會(huì)考慮使用 itertools
中的 izip
函數(shù)來處理您不想創(chuàng)建新列表的非常長(zhǎng)的列表.
If you use Python 2 (not suggested) you might consider using the izip
function in itertools
for very long lists where you don't want to create a new list.
import itertools
for first, second in itertools.izip(l, l[1:]):
...
這篇關(guān)于遍歷列表中的所有連續(xù)項(xiàng)對(duì)的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!