试图弄清楚我的代码关于列表有什么问题?
trying to figure out what's wrong with my code regarding lists?
所以我刚开始编码,我选择了 python。我在处理列表时发现有些奇怪。
wishPlaces = ["Tokyo","Hong Kong","New York","Paris","London"]
print("\n"+str(wishPlaces.reverse()))
如果我这样写,那么一旦执行它就会显示 "None" 结果(我使用 geany IDE)
但是我写的时候没问题:
wishPlaces = ["Tokyo","Hong Kong","New York","Paris","London"]
wishPlaces.reverse()
print("\n"+str(wishPlaces))
有人可以告诉我上一行代码有什么问题吗?
reverse()
方法是一种就地方法。这意味着它不会 return 任何东西,它只是修改列表。这就是为什么您使用 wishPlaces.reverse()
修改 wishPlaces
和 NOT wishPlaces=wishPlaces.reverse()
.
当你有 print("\n"+str(wishPlaces.reverse()))
时,你告诉 python 打印什么 wishPlaces.reverse()
是 returning,以及什么该方法 returns 是 None
(一个 Nonetype 对象)。当您使用 .reverse()
方法就地修改 wishPlaces
然后打印 wishPlaces
时,事情会按预期进行,因为您实际上已经修改了 wishPlaces
。
改为使用列表迭代:
wishPlaces = ["Tokyo","Hong Kong","New York","Paris","London"]
wishPlaces = wishPlaces[-1:0:-1]
print(wishPlaces)
[-1:0:-1]
是一种迭代语法。第一个值是起始索引; -1
表示列表中的最后一项。第二个定义整理指数。第三个值定义步骤; -1
反了。
最终代码:
wishPlaces = ["Tokyo","Hong Kong","New York","Paris","London"]
print("\n"+wishPlaces[-1:0:-1])
请注意,您不需要将列表项转换为字符串
另外 print
函数自动将新行打印到控制台 window
所以我刚开始编码,我选择了 python。我在处理列表时发现有些奇怪。
wishPlaces = ["Tokyo","Hong Kong","New York","Paris","London"]
print("\n"+str(wishPlaces.reverse()))
如果我这样写,那么一旦执行它就会显示 "None" 结果(我使用 geany IDE)
但是我写的时候没问题:
wishPlaces = ["Tokyo","Hong Kong","New York","Paris","London"]
wishPlaces.reverse()
print("\n"+str(wishPlaces))
有人可以告诉我上一行代码有什么问题吗?
reverse()
方法是一种就地方法。这意味着它不会 return 任何东西,它只是修改列表。这就是为什么您使用 wishPlaces.reverse()
修改 wishPlaces
和 NOT wishPlaces=wishPlaces.reverse()
.
当你有 print("\n"+str(wishPlaces.reverse()))
时,你告诉 python 打印什么 wishPlaces.reverse()
是 returning,以及什么该方法 returns 是 None
(一个 Nonetype 对象)。当您使用 .reverse()
方法就地修改 wishPlaces
然后打印 wishPlaces
时,事情会按预期进行,因为您实际上已经修改了 wishPlaces
。
改为使用列表迭代:
wishPlaces = ["Tokyo","Hong Kong","New York","Paris","London"]
wishPlaces = wishPlaces[-1:0:-1]
print(wishPlaces)
[-1:0:-1]
是一种迭代语法。第一个值是起始索引; -1
表示列表中的最后一项。第二个定义整理指数。第三个值定义步骤; -1
反了。
最终代码:
wishPlaces = ["Tokyo","Hong Kong","New York","Paris","London"]
print("\n"+wishPlaces[-1:0:-1])
请注意,您不需要将列表项转换为字符串
另外 print
函数自动将新行打印到控制台 window