Python3 list 排序函数详解

ztenv 2020-11-13 13:00:03
Python 函数 python3 排序 List


Python3 list 排序函数详解

一、           列表的sort排序函数

函数原型:

         list.sort(key=None,reverse=False)

函数功能:

对原列表进行排序,完成排序后,原列表变为有序列表。默认情况(不传入任何参数时)按字典顺序排序。

函数参数:

(1)     key: 主要是用来进行比较的元素,只有一个参数,具体的函数的参数就是取自于可迭代对象中。指定可迭代对象中的一个元素来进行排序指定排序时使用的单个元素或多个元素、lambda表达式;

(2)     reverse:指字排序规则是升序还是降序,默认为升序排序;

二、           排序示例

1.      字符串排序

def list_sort_string():
list=["delphi","Delphi","python","Python","c++","C++","c","C","golang","Golang"]
list.sort() #按字典顺序升序排列
print("升序:",list)
list.sort(reverse=True) #按降序排列
print("降序:",list)

 

排序结果:

 

升序: ['C', 'C++', 'Delphi', 'Golang', 'Python', 'c', 'c++', 'delphi', 'golang', 'python']
降序: ['python', 'golang', 'delphi', 'c++', 'c', 'Python', 'Golang', 'Delphi', 'C++', 'C']

2.      数值型排序

def list_sort_number():
list=[30,40,10,50,50.1,80,60,100,90]
list.sort()
print("升序:",list)
list.sort(reverse=True)
print("降序:",list)

排序结果:

升序: [10, 30, 40, 50, 50.1, 60, 80, 90, 100]
降序: [100, 90, 80, 60, 50.1, 50, 40, 30, 10]

 

3.      根据列表中类对象的属性排序

 

class element(object):
def __init__(self,id="",name=""):
self.id=id
self.name=name
def __lt__(self, other): # override <操作符
if self.id<other.id:
return True
return False
def __str__(self): # override __str__
return "id={0},name={1}".format(self.id,self.name)
def sort_by_attribute():
list=[element(id="130",name="json"),
element(id="01",name="jack"),element(id="120",name="tom")]
list.sort()
for item in list:
print(item)

 

由于list.sort()函数在排序时,使用的是小于号对比,所以自定义的数据类型需要override __lt__(小于)函数才能实现排序。

 

根据element的id属性排序

排序列的结果:

id=01,name=jack
id=120,name=tom
id=130,name=json

4.      根据列表中元素的长度排序

def list_sort_by_length():
list=["delphi","Delphi","python","Python","c++","C++","c","C","golang","Golang"]
list.sort(key=lambda ele:len(ele)) #按元素长度顺序升序排列
print("升序:",list)
list.sort(key=lambda ele:len(ele),reverse=True) #按降序排列
print("降序:",list)

 

借助于lambda表达式,计算list列表中的元素的长度,根据元素的长度进行排序

 

排序的结果:

升序: ['c', 'C', 'c++', 'C++', 'delphi', 'Delphi', 'python', 'Python', 'golang', 'Golang']
降序: ['delphi', 'Delphi', 'python', 'Python', 'golang', 'Golang', 'c++', 'C++', 'c', 'C']

 

5.      根据列表中元素的多个属性进行排序:

 

def two_d_list_sort():
list=[ ["1","c++","demo"],
["1","c","test"],
["2","java",""],
["8","golang","google"],
["4","python","gil"],
["5","swift","apple"]
]
list.sort(key=lambda ele:ele[0])# 根据第1个元素排序
print(list)
list.sort(key=lambda ele:ele[1]) #先根据第2个元素排序
print(list)
list.sort(key=lambda ele:(ele[1],ele[0])) #先根据第2个元素排序,再根据第1个元素排序
print(list)

 

同样借助于lambda表达式完成,当然也可以定义一个与labmda具有相同意义的函数实现排序。

 

排序结果:

[['1', 'c++', 'demo'], ['1', 'c', 'test'], ['2', 'java', ''], ['4', 'python', 'gil'], ['5', 'swift', 'apple'], ['8', 'golang', 'google']]
[['1', 'c', 'test'], ['1', 'c++', 'demo'], ['8', 'golang', 'google'], ['2', 'java', ''], ['4', 'python', 'gil'], ['5', 'swift', 'apple']]
[['1', 'c++', 'demo'], ['1', 'c', 'test'], ['8', 'golang', 'google'], ['2', 'java', ''], ['4', 'python', 'gil'], ['5', 'swift', 'apple']]

 

6.      动态的根据用户指定的索引进行排序

 

有时候,在写代码之前,并不知道根据二维表的哪几列排序,而是在程序运行的时候根据输入或配置决定的,为了解决这个动态根据多个列或属性排序的问题,借助了eval()函数,eval函数能够把字符串编译成python代码并运行,从而达到动态根据多个列或属性排序的目的。

排序结果:

排序索引: 0 [['1', 'c++', 'demo'], ['1', 'c', 'test'], ['2', 'java', ''], ['4', 'python', 'gil'], ['5', 'swift', 'apple'], ['8', 'golang', 'google']]
排序索引: 1 [['1', 'c', 'test'], ['1', 'c++', 'demo'], ['8', 'golang', 'google'], ['2', 'java', ''], ['4', 'python', 'gil'], ['5', 'swift', 'apple']]
排序索引: 2 [['2', 'java', ''], ['5', 'swift', 'apple'], ['1', 'c++', 'demo'], ['4', 'python', 'gil'], ['8', 'golang', 'google'], ['1', 'c', 'test']]
排序索引: 1,0 [['1', 'c++', 'demo'], ['1', 'c', 'test'], ['8', 'golang', 'google'], ['2', 'java', ''], ['4', 'python', 'gil'], ['5', 'swift', 'apple']]

 

综上,基本总结了list.sort的使用的大部分场景,如下:

 

1、默认排序

2、根据类对象的单个属性进行排序,当然也可以扩展为根据类对象的多个属性进行排序

3、根据元素的固有属性进行排序,如:长度、第N个元素等。为了简单,所以借助了lambda表达式,当然也可以使用普通函数代替lambda表达式

4、动态的根据多个列进行排序,同时借助lambda和eval()函数实现

5、另外相比Python2,Python3取消了sort函数中的 cmp方式,只能用key方式。
      所以python2用cmp方式写的函数迁移到python3中需要转换。
     from functools import cmp_to_key

    sort(iterable, key=cmp_to_key(cmp_fun))

   <感谢CSDN:xpresslink的指正>

可能还有一些场景没有涉及到,不过我相信,上面的几种情况可以满足90%以上的场景了;如果在使用中有问题欢迎留言交流。

版权声明
本文为[ztenv]所创,转载请带上原文链接,感谢
https://blog.csdn.net/lianshaohua/article/details/80483357

  1. 利用Python爬虫获取招聘网站职位信息
  2. Using Python crawler to obtain job information of recruitment website
  3. Several highly rated Python libraries arrow, jsonpath, psutil and tenacity are recommended
  4. Python装饰器
  5. Python实现LDAP认证
  6. Python decorator
  7. Implementing LDAP authentication with Python
  8. Vscode configures Python development environment!
  9. In Python, how dare you say you can't log module? ️
  10. 我收藏的有关Python的电子书和资料
  11. python 中 lambda的一些tips
  12. python中字典的一些tips
  13. python 用生成器生成斐波那契数列
  14. python脚本转pyc踩了个坑。。。
  15. My collection of e-books and materials about Python
  16. Some tips of lambda in Python
  17. Some tips of dictionary in Python
  18. Using Python generator to generate Fibonacci sequence
  19. The conversion of Python script to PyC stepped on a pit...
  20. Python游戏开发,pygame模块,Python实现扫雷小游戏
  21. Python game development, pyGame module, python implementation of minesweeping games
  22. Python实用工具,email模块,Python实现邮件远程控制自己电脑
  23. Python utility, email module, python realizes mail remote control of its own computer
  24. 毫无头绪的自学Python,你可能连门槛都摸不到!【最佳学习路线】
  25. Python读取二进制文件代码方法解析
  26. Python字典的实现原理
  27. Without a clue, you may not even touch the threshold【 Best learning route]
  28. Parsing method of Python reading binary file code
  29. Implementation principle of Python dictionary
  30. You must know the function of pandas to parse JSON data - JSON_ normalize()
  31. Python实用案例,私人定制,Python自动化生成爱豆专属2021日历
  32. Python practical case, private customization, python automatic generation of Adu exclusive 2021 calendar
  33. 《Python实例》震惊了,用Python这么简单实现了聊天系统的脏话,广告检测
  34. "Python instance" was shocked and realized the dirty words and advertisement detection of the chat system in Python
  35. Convolutional neural network processing sequence for Python deep learning
  36. Python data structure and algorithm (1) -- enum type enum
  37. 超全大厂算法岗百问百答(推荐系统/机器学习/深度学习/C++/Spark/python)
  38. 【Python进阶】你真的明白NumPy中的ndarray吗?
  39. All questions and answers for algorithm posts of super large factories (recommended system / machine learning / deep learning / C + + / spark / Python)
  40. [advanced Python] do you really understand ndarray in numpy?
  41. 【Python进阶】Python进阶专栏栏主自述:不忘初心,砥砺前行
  42. [advanced Python] Python advanced column main readme: never forget the original intention and forge ahead
  43. python垃圾回收和缓存管理
  44. java调用Python程序
  45. java调用Python程序
  46. Python常用函数有哪些?Python基础入门课程
  47. Python garbage collection and cache management
  48. Java calling Python program
  49. Java calling Python program
  50. What functions are commonly used in Python? Introduction to Python Basics
  51. Python basic knowledge
  52. Anaconda5.2 安装 Python 库(MySQLdb)的方法
  53. Python实现对脑电数据情绪分析
  54. Anaconda 5.2 method of installing Python Library (mysqldb)
  55. Python implements emotion analysis of EEG data
  56. Master some advanced usage of Python in 30 seconds, which makes others envy it
  57. python爬取百度图片并对图片做一系列处理
  58. Python crawls Baidu pictures and does a series of processing on them
  59. python链接mysql数据库
  60. Python link MySQL database