Python - 为什么 reverse 函数在给定列表时不起作用,但对变量起作用?

Python - Why doesn't the reverse function doesn't work when given with list but does work with the variable?

初学者问题...

为什么会这样?为什么 reverse 函数在给定列表时不起作用,但对变量起作用?

>>> a=[1,2].reverse()
>>> a      <--- a is None
>>> a=[1,2]
>>> a.reverse()
>>> a      <--- a is not None and doing what I wanted him to do
[2, 1]
>>>  

确实有效。 Python 中的列表 reverse 方法没有 return 反向列表(它没有 return 任何东西 == returns None),它反转它应用到位的列表。当你在列表文字上调用它时,它实际上是颠倒的,但没有办法获得颠倒的列表。

reversed 函数 (https://docs.python.org/3/library/functions.html#reversed) 可以满足您的期望

  1. reverse() 没有 return 任何值,即它 returns None.
  2. Reverse() 就地修改列表。

在你的第一种情况下,你依次设置 ​​a = None.

在你的第二种情况下,a被reverse()修改,你可以打印修改后的“a”。

那是因为reverse() returns None,但是它颠倒了列表中项目的顺序。

例如,

>>>a = [1, 2].reverse() # It reversed [1, 2] to [2, 1] but returns None. 
>>>a # The reversed value of [2, 1] disappears, 
# And returned value of None has been assigned to variable a
None
>>>a=[1,2] 
>>>a.reverse() # The order of items of a has been reversed and return None, 
# but there is no variable to take returned value, None.
>>> a
[2, 1]