python - reverse() 在 python 中的用法?

标签 python reverse

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/

相关文章:

python - Sublime Text 3插件Python 3从其他文件夹导入包

javascript - ReverseArrayInPlace 奇怪的错误?

c++ - 递归逆函数

Python:在不改变段落顺序的情况下反转文件每个段落中的单词?

python - 如何获取模块中的所有变量,但不包括在该模块中导入的变量

python - 根据首字母修改字符串内容

python - Tkinter Listbox 如何判断是否选择了某个项目

javascript - keydown 上的反转图像 - Javascript

jQuery 删除一个元素并对剩余元素重新编号

python - Seq2Seq 模型 Tensorflow 中的输出投影