The sort() and reverse() methods modify the list in place for economy of space when sorting or reversing a large list. To remind you that they operate by side effect, they don’t return the sorted or reversed list.
以上文字可在http://docs.python.org/2/library/stdtypes.html#mutable-sequence-types找到
“修改列表以节省空间”是什么意思?
示例:
x = ["happy", "sad"]
y = x.reverse()
会将 None
返回给 y
。那么为什么,
x.reverse()
成功反转x
?
最佳答案
What does "modify the list in place for economy of space" mean?
这意味着它不会创建列表的副本。
why does, x.reverse() Successfully reverse x?
我不明白这个问题。它这样做是因为这是它的设计目的(反转 x
并返回 None
)。
请注意,sort()
和 reverse()
具有不修改原件并返回副本的对应项。这些函数称为 sorted()
和 reversed()
:
In [7]: x = [1, 2, 3]
In [8]: y = list(reversed(x))
In [9]: x
Out[9]: [1, 2, 3]
In [10]: y
Out[10]: [3, 2, 1]
关于python - reverse() 在 python 中的用法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21958477/