【问题标题】:Print list backwards in Python在 Python 中向后打印列表
【发布时间】:2014-09-27 20:25:37
【问题描述】:

我知道有更好的方法可以向后打印。但由于某种原因,我无法让它工作。任何想法为什么?

fruit = 'banana'
index = 0
while index < len(fruit):
    print fruit[-(index)]
    index = index + 1

【问题讨论】:

标签: python list printing reverse


【解决方案1】:

除了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

注意开头的a,然后正确反转pple

index = index + 1 上移一行:

index = 0
while index < len(fruit):
    index = index + 1
    print fruit[-index]

现在您使用索引 -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

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

【讨论】:

  • 其中一种奇怪的情况,很难调试的唯一原因是使用的特定示例。没有多少单词是一个字母后跟一个回文。
猜你喜欢
  • 1970-01-01
  • 2015-09-16
  • 2015-07-14
  • 1970-01-01
  • 2017-08-10
  • 1970-01-01
  • 1970-01-01
  • 2017-11-16
  • 1970-01-01
相关资源
最近更新 更多