是否应为内置Python函数sort()导入库

时间:2014-08-02 22:48:01

标签: python python-2.7

我有以下用Python 2.7编写的程序

numbers = [25, 03, 91, 59, 10, 12, 6, 9]
print(numbers)
print (numbers.sort())

输出结果为:

[25, 3, 91, 59, 10, 12, 6, 9]
None

为什么返回无?

2 个答案:

答案 0 :(得分:3)

它正在返回None,因为sort()会更改列表,但不会返回新列表:

>>>> numbers = [25, 03, 91, 59, 10, 12, 6, 9]
>>>> print(numbers)
[25, 3, 91, 59, 10, 12, 6, 9]
>>>> numbers.sort()
>>>> print(numbers)
[3, 6, 9, 10, 12, 25, 59, 91]

答案 1 :(得分:1)

Python的sort()对列表进行排序并返回None。如果要打印已排序的列表,只需再次打印列表。

numbers = [1,4,2,3,5]
print(numbers)  # prints [1,4,2,3,5]
numbers.sort()
print(numbers)  # prints [1,2,3,4,5]

此外,Python有一个内置sorted(),它返回列表的副本,已排序。

numbers = [1,4,2,3,5]
print(numbers)          # prints [1,4,2,3,5]
print(sorted(numbers))  # prints [1,2,3,4,5]