【问题标题】:I want to use function sort in python 3.7.4 but I can't. Why? [duplicate]我想在 python 3.7.4 中使用函数排序,但我不能。为什么? [复制]
【发布时间】:2019-06-15 18:10:18
【问题描述】:

在 python 3.7.4 中,我想对数组进行排序,但我不能。我使用函数排序并编写了这段代码 -

arr = [0,5,8,9,6,3,1,2]
print(arr.sort())

输出

None

请帮帮我。

【问题讨论】:

  • .sort() 是一个就地方法,意味着它对列表进行排序(并且列表被修改)并返回 NoneType。尝试print(arr) 查看排序列表。
  • print(sorted(arr)) 会做你想做的事。

标签: python list sorting


【解决方案1】:

Python 的list.sort() 就地修改列表并且不返回它。例如:

x = [0,5,8,9,6,3,1,2]
print(x)  # [0, 5, 8, 9, 6, 3, 1, 2]

x.sort()
print(x)  # [0, 1, 2, 3, 5, 6, 8, 9]

有关list 方法的更多信息,请参阅the docs

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-04-02
    • 1970-01-01
    • 2015-05-28
    • 2017-05-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多