首页 > 编程语言 >python中sorted排序

python中sorted排序

时间:2023-03-26 17:33:07浏览次数:38  
标签:24 12 15 python key sorted 排序

 

key是自定义函数
reverse=False,升序(默认)
reverse=True,倒序
#不区分大小写排序
sorted(['bob', 'aBout', 'ZOO', 'Credit'],key=str.lower)

#按绝对值排序
sorted([36, 5, -12, 9, -21], key=abs)

L = [('Bob', 75), ('adam', 92), ('Bart', 66), ('Lisa', 88)]

# key 相当于遍历了L,即x = [i for i in L],那么x[0]取的就是元组的第一个值
#按姓名排序
print(sorted(L,key=lambda x:x[0]))
#按姓名排序不分大小写
print(sorted(L,key=lambda x:x[0].lower()))
#按成绩倒序排序
print(sorted(L,key=lambda x:x[1],reverse=True))

 

data = [(12, 24), (12, 15), (15, 24), (7, 30), (30, 24)]
print(sorted(data, key=lambda x:(x[0], x[1]))) #根据元祖第一个值升序排序,若第一个值相等则根据第二个值升序排序
print(sorted(data, key=lambda x:(x[0], -x[1])))#根据元祖第一个值升序排序,若第一个值相等则根据第二个值降序排序

#输出
[(7, 30), (12, 15), (12, 24), (15, 24), (30, 24)]
[(7, 30), (12, 24), (12, 15), (15, 24), (30, 24)]


#同时也可通过传入自定义函数进行排序,两者结果一致
def cmp1(x):
return x[0], x[1]
def cmp2(x):
return x[0], -x[1]
print(sorted(data, key=cmp1)) #根据元祖第一个值升序排序,若第一个值相等则根据第二个值升序排序
print(sorted(data, key=cmp2)) #根据元祖第一个值升序排序,若第一个值相等则根据第二个值降序排序

#输出
[(7, 30), (12, 15), (12, 24), (15, 24), (30, 24)]
[(7, 30), (12, 24), (12, 15), (15, 24), (30, 24)]

 

标签:24,12,15,python,key,sorted,排序
From: https://www.cnblogs.com/ricehome/p/17259039.html

相关文章

  • python-concurrent
    python-concurrent概述__all__=('FIRST_COMPLETED','FIRST_EXCEPTION','ALL_COMPLETED','CancelledError','TimeoutError','BrokenExec......
  • python-threading
    python-threading目录python-threadingthreadingThread创建线程Thread方法属性守护线程线程锁Lockthreading.Lockthreading.RLock事件对象EventConditionTimerimportthr......
  • 关于python中的OSError报错问题
    Traceback(mostrecentcalllast): File"main.py",line1,in<module>   fromtrainerimportTrainer File"/home/visionx/mt/qg/paragraph_nqg_max_point_......
  • Python--模块--pymysql
    如何使用?建立连接--》建立游标--》执行命令...#pip3installpymysqlimportpymysqlconn=pymysql.connect(host="127.0.0.1",port=3306,database="day35",user......
  • python之终止代码运行之raise
    raise函数可以终止代码的运行print('hello')raise'终止运行,并报异常'print('word')执行结果>>>:helloTraceback(mostrecentcalllast):File"D:/Users/720......
  • 在不同操作系统上安装Python的详细教程
    Windows打开Python官方网站(https://www.python.org/downloads/)并下载最新版本的Python。选择适合您操作系统的版本。如果您使用的是64位的Windows系统,请下载64位版本。如果......
  • 【Python】连接MySQL报错:RuntimeError 'cryptography' package is required for sha25
    ✨报错提示RuntimeError:'cryptography'packageisrequiredforsha256_passwordorcaching_sha2_passwordauthmethods✨解决方案pipinstallcryptography......
  • 排序算法
    排序算法本文默认升序(从小到大)排序1.入门排序1.1选择排序在后(n-i)个元素中找到一个最小的,放在第i位。时间复杂度为O(\(n^2\))。代码实现如下:for(inti=0;i<n;i+......
  • 插入排序
      代码实现:publicclass插入排序{publicstaticvoidmain(String[]args){int[]array={3,44,38,44,72,54,32,43,242,46,47,56};//定义一......
  • 选择排序
      代码实现:publicclass选择排序{publicstaticvoidmain(String[]args){int[]array={2,5,4,3,1};//外循环:i表示我拿着哪个索引进行比......