文章来自《Python cookbook》.

翻译仅仅是为了个人学习,其它商业版权纠纷与此无关!

-- Zoom.Quiet [DateTime(2004-08-11T01:21:53Z)] TableOfContents

在索引和序列元素上并行循环

1.14 Looping in Parallel over Index and Sequence Items

Credit: Alex Martelli

问题 Problem

You need to loop on a sequence, but at each step you also need to know what index into the sequence you have reached.


/!\ Edit conflict! Other version:


你霥8POST http://wiki.woodpecker.org.cn/moin.cgi/PyCkBk_2d1_2d14 HTTP/1.0 Accept: image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/x-shockwave-flash, */* Referer: http://wiki.woodpecker.org.cn/moin.cgi/PyCkBk_2d1_2d14 Accept-Language: zh-cn Content-Type: application/x-www-form-urlencoded User-Agent: Mozilla/4.0 (compatible


/!\ Edit conflict! Your version:


你需要在一个序列上循环,但是在每一步,你也需要知道什么索引进入到你已经到达的序列中。

解决 Solution

Together, the built-in functions xrange and zip make this easy. You need only this one instance of xrange, as it is fully reusable:

把内建函数xrange和zip放在一起将使它很容易。你只需要xrange的一个实例,好像它完全可重用。

indices = xrange(sys.maxint) 

Here's how you use the indices instance:

这儿是你怎么样使用index的实例

   1 for item, index in zip(sequence, indices):
   2     something(item, index)

This gives the same semantics as:

给出相同的语义:

   1 for index in range(len(sequence)):
   2     something(sequence[index], index)

but the change of emphasis allows greater clarity in many usage contexts.

但是改变的重点允许在更多使用环境中更加清楚。

Another alternative is to use class wrappers:

另一个可选择的是使用一个包装类:

   1 class Indexed:
   2     def _ _init_ _(self, seq):
   3         self.seq = seq
   4     def _ _getitem_ _(self, i):
   5         return self.seq[i], i

For example:

例如

   1 for item, index in Indexed(sequence):
   2     something(item, index)

In Python 2.2, with from _ _future_ _ import generators, you can also use:

在python2.2, 从_ _future_ _导入一个产生器, 你也可以使用:

   1 def Indexed(sequence):
   2     iterator = iter(sequence)
   3     for index in indices:
   4         yield iterator.next(  ), index
   5     # Note that we exit by propagating StopIteration when .next raises it!

However, the simplest roughly equivalent way remains the good old:

然而,最简单粗糙的等价方法仍然是老的: