python中的排序

今天在http://www.pythontip.com刷题的时候遇到一个排序的问题:一个列表中既有字符串,又有数字,该怎么排序。

list = [1,2,5,4,'d','s','e',45]
list.sort()

如果直接调用sort()函数则会报

TypeError                                 Traceback (most recent call last)
<ipython-input-9-f338e0e85925> in <module>()
----> 1 list.sort()

TypeError: '<' not supported between instances of 'str' and 'int'

我理解的是sort()函数内部是通过'<'来完成大小的比较,而'<'不支持对字符串和数字之间的的比较。

后来发现有个sorted()函数可解决字符串和数字一起的排序问题

new_list = sorted(list)

sorted()跟sort()的调用方式不太一样,sorted()是将欲排序的list作为参数传入,然后得到排序后的list,而sort()是在原list的基础上进行排序。

sort()函数仅定义在list中,而sorted()对所有的可迭代对象都有效。

通过help()查看下两者区别:

---------------------------------sorted----------------------------------------

In [14]: help(list.sort)
Help on built-in function sort:

sort(...) method of builtins.list instance
L.sort(key=None, reverse=False) -> None -- stable sort *IN PLACE*

--------------------------------sorted---------------------------------------

In [15]: help(sorted)
Help on built-in function sorted in module builtins:

sorted(iterable, /, *, key=None, reverse=False)
Return a new list containing all items from the iterable in ascending order.

A custom key function can be supplied to customize the sort order, and the
reverse flag can be set to request the result in descending order.

升序返回一个新的列表包含所有项目的迭代。

可以提供自定义key函数以自定义排序顺序,可以设置反向标志以按降序返回结果。

原文地址:https://www.cnblogs.com/wulaa/p/7857080.html