反转具有单个元素的列表给出 None
Reversing a list with single element gives None
我注意到从函数返回一个列表(只有一个元素)然后尝试使用 reverse() 反转它时的奇怪行为
我在这里提炼了它:
def myFunction():
return ["The Smiths"]
nums = [5,4,3,2,1]
nums.reverse()
print nums # 1,2,3,4,5 - fine!
# lets use one element in a list
something = ["Gwen Stefani"]
something.reverse()
print something # ["Gwen Stefani"] also fine
# now let's do the same, but from a function
a = myFunction()
print a # The Smiths
print a.reverse() # None
print a[::-1] # The Smiths
我需要大人来解释创建 None 的原因,而不是 [::-1].
中看到的单个元素
list.reverse()
就地反转列表,但函数本身不会 return 任何东西。
a = ["The Smiths"]
print a # The Smiths
print a.reverse() # None
print a # It's already there
我注意到从函数返回一个列表(只有一个元素)然后尝试使用 reverse() 反转它时的奇怪行为
我在这里提炼了它:
def myFunction():
return ["The Smiths"]
nums = [5,4,3,2,1]
nums.reverse()
print nums # 1,2,3,4,5 - fine!
# lets use one element in a list
something = ["Gwen Stefani"]
something.reverse()
print something # ["Gwen Stefani"] also fine
# now let's do the same, but from a function
a = myFunction()
print a # The Smiths
print a.reverse() # None
print a[::-1] # The Smiths
我需要大人来解释创建 None 的原因,而不是 [::-1].
中看到的单个元素list.reverse()
就地反转列表,但函数本身不会 return 任何东西。
a = ["The Smiths"]
print a # The Smiths
print a.reverse() # None
print a # It's already there