SMILET
.sort()和.reverse()更改列表就位回归None见可变序列文档:这个sort()和reverse()方法在排序或反转大列表时,为节省空间而修改列表。为了提醒您,它们是按副作用操作的,它们不会返回排序列表或反向列表。而是这样做:a.sort()print(a)a.reverse()print(a)或使用sorted()和reversed()职能。print(sorted(a)) # just sortedprint(list(reversed(a))) # just reversedprint(a[::-1]) # reversing by using a negative slice stepprint(sorted(a, reverse=True)) # sorted *and* reversed这些方法返回一个新的列出并保持原始输入列表不变。演示、就地排序和倒转:>>> 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]并创建新的排序和反向列表:>>> 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]
撒科打诨
一个简单的升序排序非常容易,调用排序()函数。它返回一个新的排序列表:>>> sorted([66.25, 333, 333, 1, 1234.5])[1, 66.25, 333, 333, 1234.5]接受带有布尔值的反向参数。>>> sorted([66.25, 333, 333, 1, 1234.5], reverse=True)[1234.5, 333, 333, 66.25, 1]