如何在python中向后循环?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3476732/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 11:16:11  来源:igfitidea点击:

How to loop backwards in python?

pythoniterationrange

提问by snakile

I'm talking about doing something like:

我说的是做类似的事情:

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

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

我可以想到在 python 中这样做的一些方法(创建一个列表range(1,n+1)并反转它,使用whileand --i,...)但我想知道是否有更优雅的方法来做到这一点。在那儿?

EDIT: 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.

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

采纳答案by Chinmay Kanchi

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

range()xrange()采用指定步骤的第三个参数。因此,您可以执行以下操作。

range(10, 0, -1)

Which gives

这使

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

But for iteration, you should really be using xrangeinstead. So,

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

xrange(10, 0, -1)

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

Python 3 用户注意事项:Python 3 中没有单独的rangexrange函数,只有range,它遵循 Python 2 的xrange.

回答by habnabit

for x in reversed(whatever):
    do_something()

This works on basically everything that has a defined order, including xrangeobjects and lists.

这基本上适用于具有定义顺序的所有内容,包括xrange对象和列表。

回答by alex.hunter

To reverse a string without using reversedor [::-1], try something like:

要在不使用reversed或的情况下反转字符串[::-1],请尝试以下操作:

def reverse(text):
    # Container for reversed string
    txet=""

    # store the length of the string to be reversed
    # account for indexes starting at 0
    length = len(text)-1

    # loop through the string in reverse and append each character
    # deprecate the length index
    while length>=0:
        txet += "%s"%text[length]
        length-=1
    return txet

回答by Michael Qin

def reverse(text):
    reversed = ''
    for i in range(len(text)-1, -1, -1):
        reversed += text[i]
    return reversed

print("reverse({}): {}".format("abcd", reverse("abcd")))

回答by chocolate codes

All of these three solutions give the same results if the input is a string:

如果输入是字符串,所有这三种解决方案都会给出相同的结果:

1.

1.

def reverse(text):
    result = ""
    for i in range(len(text),0,-1):
        result += text[i-1]
    return (result)

2.

2.

text[::-1]

3.

3.

"".join(reversed(text))