[英]Print list backwards in Python
I know there are better ways to print things backwards. 我知道有更好的方法可以向后打印内容。 But for some reason I can't get this to work.
但是由于某种原因,我无法使它正常工作。 Any ideas why?
有什么想法吗?
fruit = 'banana'
index = 0
while index < len(fruit):
print fruit[-(index)]
index = index + 1
You reversed everything but the b
, because you started at 0, and -0 is still 0. 您将
b
所有内容都反转了,因为您从0开始,并且-0仍然为0。
You end up with the indices 0, -1, -2, -3, -4, -5, and thus print b
, then only anana
in reverse. 您最终得到的索引为0,-1,-2,-3,-4,-5,因此打印
b
,然后仅打印anana
。 But anana
is a palindrome, so you cannot tell what happened! 但是
anana
是回文,所以您无法判断发生了什么! Had you picked another word it would have been clearer: 如果您选择了另一个词,它将更加清楚:
>>> fruit = 'apple'
>>> index = 0
>>> while index < len(fruit):
... print fruit[-index]
... index = index + 1
...
a
e
l
p
p
Note the a
at the start, then pple
correctly reversed. 请注意开头的
a
,然后正确将pple
颠倒过来。
Move the index = index + 1
up a line: 将
index = index + 1
向上移动一行:
index = 0
while index < len(fruit):
index = index + 1
print fruit[-index]
Now you use the indices -1, -2, -3, -4, -5 and -6 instead: 现在,您改为使用索引-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
I removed the (..)
in the expression -(index)
as it is redundant. 我删除了表达式
-(index)
的(..)
,因为它是多余的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.