在Python中向后打印列表

bug*_*syb 0 python printing reverse list

我知道有更好的方法可以向后打印东西.但由于某种原因,我不能让这个工作.有什么想法吗?

fruit = 'banana'
index = 0
while index < len(fruit):
    print fruit[-(index)]
    index = index + 1
Run Code Online (Sandbox Code Playgroud)

Mar*_*ers 6

你反转了除了之外的一切b,因为你从0开始,-0仍然是0.

你最终得到索引0,-1,-2,-3,-4,-5,然后打印b,然后只anana反过来.但是anana是回文,所以你不知道发生了什么!如果你选择了另一个词,它会更清楚:

>>> fruit = 'apple'
>>> index = 0
>>> while index < len(fruit):
...     print fruit[-index]
...     index = index + 1
... 
a
e
l
p
p
Run Code Online (Sandbox Code Playgroud)

注意a在开始时,然后pple正确反转.

移动index = index + 1 一行:

index = 0
while index < len(fruit):
    index = index + 1
    print fruit[-index]
Run Code Online (Sandbox Code Playgroud)

现在你使用索引-1,-2,-3,-4,-5和-6代替:

>>> fruit = 'banana'
>>> index = 0
>>> while index < len(fruit):
...     index = index + 1
...     print fruit[-index]
... 
a
n
a
n
a
b
>>> fruit = 'apple'
>>> index = 0
>>> while index < len(fruit):
...     index = index + 1
...     print fruit[-index]
... 
e
l
p
p
a
Run Code Online (Sandbox Code Playgroud)

我删除了(..)表达式,-(index)因为它是多余的.