sort()和reverse()函数不起作用 [英] sort() and reverse() functions do not work

查看:286
本文介绍了sort()和reverse()函数不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图根据我正在阅读的教程测试python中的列表如何工作. 当我尝试使用list.sort()list.reverse()时,解释器给了我None.

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().reverse()在适当的位置更改列表 并返回None参见

.sort() and .reverse() change the list in place and return None See the mutable sequence documentation:

sort()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.

相反,请执行以下操作:

Do this instead:

a.sort()
print(a)
a.reverse()
print(a)

或使用 sorted()

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

这些方法返回一个 new 列表,并保持原始输入列表不变.

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()函数不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆