问题描述
我试图根据我正在阅读的教程测试 python 中的列表是如何工作的.当我尝试使用 list.sort()
或 list.reverse()
时,解释器给了我 None
.
请告诉我如何从这两种方法中获得结果:
a = [66.25, 333, 333, 1, 1234.5]打印(a.sort())打印(a.reverse())
.sort()
和 .reverse()
更改列表就地 并返回 None
参见 mutable序列文档:
sort()
和 reverse()
方法在排序或反转大列表时修改列表以节省空间.提醒您它们是通过副作用操作的,它们不会返回排序或反转的列表.
改为这样做:
a.sort()打印(一)a.反向()打印(一)
或使用 sorted()
和 reversed()
函数.
print(sorted(a)) # 刚刚排序print(list(reversed(a))) # 刚刚反转print(a[::-1]) # 使用负切片步骤反转print(sorted(a, reverse=True)) # sorted *and* reversed
这些方法返回一个新列表并保持原始输入列表不变.
演示,就地排序和反转:
>>>a = [66.25, 333, 333, 1, 1234.5]>>>a.sort()>>>打印(一)[1, 66.25, 333, 333, 1234.5]>>>a.反向()>>>打印(一)[1234.5, 333, 333, 66.25, 1]并创建新的排序和反向列表:
>>>a = [66.25, 333, 333, 1, 1234.5]>>>打印(排序(一))[1, 66.25, 333, 333, 1234.5]>>>打印(列表(反转(a)))[1234.5, 1, 333, 333, 66.25]>>>打印(a[::-1])[1234.5, 1, 333, 333, 66.25]>>>打印(排序(一个,反向=真))[1234.5, 333, 333, 66.25, 1]>>>a # 输入列表未受影响[66.25, 333, 333, 1, 1234.5]I was trying to test how the lists in python works according to a tutorial I was reading.When I tried to use list.sort()
or list.reverse()
, the interpreter gives me None
.
Please let me know how I can get a result from these two methods:
a = [66.25, 333, 333, 1, 1234.5]
print(a.sort())
print(a.reverse())
.sort()
and .reverse()
change the list in place and return None
See the mutable sequence documentation:
Do this instead:
a.sort()
print(a)
a.reverse()
print(a)
or use the sorted()
and reversed()
functions.
print(sorted(a)) # just sorted
print(list(reversed(a))) # just reversed
print(a[::-1]) # reversing by using a negative slice step
print(sorted(a, reverse=True)) # sorted *and* reversed
These methods return a new list and leave the original input list untouched.
Demo, in-place sorting and reversing:
>>> a = [66.25, 333, 333, 1, 1234.5]
>>> a.sort()
>>> print(a)
[1, 66.25, 333, 333, 1234.5]
>>> a.reverse()
>>> print(a)
[1234.5, 333, 333, 66.25, 1]
And creating new sorted and reversed lists:
>>> a = [66.25, 333, 333, 1, 1234.5]
>>> print(sorted(a))
[1, 66.25, 333, 333, 1234.5]
>>> print(list(reversed(a)))
[1234.5, 1, 333, 333, 66.25]
>>> print(a[::-1])
[1234.5, 1, 333, 333, 66.25]
>>> print(sorted(a, reverse=True))
[1234.5, 333, 333, 66.25, 1]
>>> a # input list is untouched
[66.25, 333, 333, 1, 1234.5]
这篇关于sort() 和 reverse() 函数不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!