如何在python中向后循环?

问题描述:

我正在谈论的事情如下:

I'm talking about doing something like:

for(i=n; i>=1; --i) {
   //do something with i
}

我能想到的一些方法在python中创建(创建一个范围列表(1,n + 1)并使用反转它,而 - 我,...)但我想知道是否有一种更优雅的方式来做到这一点。是吗?

I can think of some ways to do so in python (creating a list of range(1,n+1) and reverse it, using while and --i, ...) but I wondered if there's a more elegant way to do it. Is there?

编辑:
有人建议我使用xrange()而不是range(),因为range返回一个列表,而xrange返回一个迭代器。但是在Python 3(我碰巧使用)中,range()返回一个迭代器而xrange不存在。

Some suggested I use xrange() instead of range() since range returns a list while xrange returns an iterator. But in Python 3 (which I happen to use) range() returns an iterator and xrange doesn't exist.

range()和 xrange()获取指定步骤的第三个参数。所以你可以做到以下几点。

range() and xrange() take a third parameter that specifies a step. So you can do the following.

range(10, 0, -1)

这给出了

[10, 9, 8, 7, 6, 5, 4, 3, 2, 1] 

但对于迭代,你应该真的使用 xrange 。所以,

But for iteration, you should really be using xrange instead. So,

xrange(10, 0, -1)




Python 3用户注意事项:没有单独的范围 xrange Python 3中的函数,只有范围,它遵循Python 2的 xrange $的设计c $ c>。

Note for Python 3 users: There are no separate range and xrange functions in Python 3, there is just range, which follows the design of Python 2's xrange.