y = [1, 3, 2, 4]
x = y.sort()
print(x)
Run Code Online (Sandbox Code Playgroud)
x 是None。为什么这种语法适用于例如 Javascript 而不是 Python?
sort(和reverse)就地更改列表。
如果你愿意,你可以使用sorted:
x = sorted(y)
Run Code Online (Sandbox Code Playgroud)
文档中的数据结构部分对此进行了解释。
在这里,y.sort()对 y 进行排序,并且不能分配给另一个变量。在这里,您可以使用sorted()like x = sorted(y)or:
x = [i for i in sorted(y)]
Run Code Online (Sandbox Code Playgroud)
或者让我们使用一个漂亮的单行:
x = [y.pop(y.index(min(y))) for i in range(len(y))]
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
770 次 |
| 最近记录: |