Python循环:以惯用方式比较列表中的连续项 [英] Python looping: idiomatically comparing successive items in a list
问题描述
我需要遍历一个对象列表,比较它们:0对1,1对2,2对3等等(我正在使用pysvn来提取差异列表。)I最后只是循环索引,但我一直想知道是否有某种方法可以做到更接近惯用。这是Python;我不应该以某种聪明的方式使用迭代器吗?简单地循环索引似乎很清楚,但我想知道是否有一种更具表现力或简洁的方法。
I need to loop over a list of objects, comparing them like this: 0 vs. 1, 1 vs. 2, 2 vs. 3, etc. (I'm using pysvn to extract a list of diffs.) I wound up just looping over an index, but I keep wondering if there's some way to do it which is more closely idiomatic. It's Python; shouldn't I be using iterators in some clever way? Simply looping over the index seems pretty clear, but I wonder if there's a more expressive or concise way to do it.
for revindex in xrange(len(dm_revisions) - 1):
summary = \
svn.diff_summarize(svn_path,
revision1=dm_revisions[revindex],
revision2 = dm_revisions[revindex+1])
推荐答案
这称为滑动窗口。
This is called a sliding window. There's an example in the itertools
documentation that does it. Here's the code:
from itertools import islice
def window(seq, n=2):
"Returns a sliding window (of width n) over data from the iterable"
" s -> (s0,s1,...s[n-1]), (s1,s2,...,sn), ... "
it = iter(seq)
result = tuple(islice(it, n))
if len(result) == n:
yield result
for elem in it:
result = result[1:] + (elem,)
yield result
你可以这样说:
for r1, r2 in window(dm_revisions):
summary = svn.diff_summarize(svn_path, revision1=r1, revision2=r2)
当然你只关心n = 2的情况,所以你可以放弃更简单的东西:
Of course you only care about the case where n=2, so you can get away with something much simpler:
def adjacent_pairs(seq):
it = iter(seq)
a = it.next()
for b in it:
yield a, b
a = b
for r1, r2 in adjacent_pairs(dm_revisions):
summary = svn.diff_summarize(svn_path, revision1=r1, revision2=r2)
这篇关于Python循环:以惯用方式比较列表中的连续项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!