网站首页 > 基础教程 正文
语法介绍
「sort 与 sorted 区别:」
sort 是应用在 list 上的方法,sorted 可以对所有可迭代的对象进行排序操作。
list 的 sort 方法返回的是对已经存在的列表进行操作,无返回值,而内建函数 sorted 方法返回的是一个新的 list,而不是在原来的基础上进行的操作。
sorted()语法:
sorted(iterable, key=None, reverse=False)
「参数说明:」
- iterable -- 可迭代对象。
- key -- 主要是用来进行比较的元素,只有一个参数,具体的函数的参数就是取自于可迭代对象中,指定可迭代对象中的一个元素来进行排序。
- reverse -- 排序规则,reverse = True 降序 , reverse = False 升序(默认)。
sort()语法:
list.sort( key=None, reverse=False)
「参数说明」:
- key -- 主要是用来进行比较的元素,只有一个参数,具体的函数的参数就是取自于可迭代对象中,指定可迭代对象中的一个元素来进行排序。
- reverse -- 排序规则,「reverse = True」 降序, 「reverse = False」 升序(默认)。
列表中有元组
L = [('b', 2), ('a', 1), ('c', 3), ('d', 4)]
L.sort(key=lambda x:x[0])
print(L)
L2 = [('b', 2), ('a', 1), ('c', 3), ('d', 4)]
sorted(L2,key=lambda x:x[0])
print(L)
students = [('john', 'A', 15), ('jane', 'B', 12), ('dave', 'B', 10)]
students.sort(key=lambda x:x[2])
print(students)
students2 = [('john', 'A', 15), ('jane', 'B', 12), ('dave', 'B', 10)]
students3 = sorted(students2,key=lambda x:x[2])
print(students3)
列表中有字典
L = [{1: 5, 3: 4}, {1: 3, 6: 3}, {1: 1, 2: 4, 5: 6}, {1: 9}]
def f(x):
return len(x)
L.sort(key=f)
print(L)
猜你喜欢
- 2024-11-22 Python 实现经典算法之堆排序
- 2024-11-22 Python版排序算法总结
- 2024-11-22 python冷门操作-11.list排序干货
- 2024-11-22 Python 排序了解一下
- 2024-11-22 Python实现冒泡排序
- 2024-11-22 Python 快速排序:高效算法一探究竟
- 2024-11-22 Python实现快速排序
- 2024-11-22 python对象自定义排序你知道吗
- 2024-11-22 Python应用——自定义排序全套方案
- 2024-11-22 Python函数知识整理
- 最近发表
- 标签列表
-
- jsp (69)
- gitpush (78)
- gitreset (66)
- python字典 (67)
- dockercp (63)
- gitclone命令 (63)
- dockersave (62)
- linux命令大全 (65)
- pythonif (86)
- location.href (69)
- dockerexec (65)
- tail-f (79)
- queryselectorall (63)
- location.search (79)
- bootstrap教程 (74)
- deletesql (62)
- linuxgzip (68)
- 字符串连接 (73)
- html标签 (69)
- c++初始化列表 (64)
- mysqlinnodbmyisam区别 (63)
- arraylistadd (66)
- mysqldatesub函数 (63)
- window10java环境变量设置 (66)
- c++虚函数和纯虚函数的区别 (66)