如何在python中向后循环? [英] How to loop backwards in python?

查看:122
本文介绍了如何在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

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.

这篇关于如何在python中向后循环?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆