本文介紹了遍歷列表中的所有連續項對的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!
問題描述
給定一個列表
l = [1, 7, 3, 5]
我想遍歷所有成對的連續列表項(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): ...
有沒有辦法使用內置的 Python 迭代器來做到這一點?我確定 itertools
模塊應該有解決方案,但我就是想不通.
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(不建議),您可能會考慮使用 itertools
中的 izip
函數來處理您不想創建新列表的非常長的列表.
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:]):
...
這篇關于遍歷列表中的所有連續項對的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!
【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持!