Python sorted函数及用法
sorted() 函数的基本语法格式如下:
list = sorted(iterable, key=None, reverse=False)
其中,iterable 表示指定的序列,key 参数可以自定义排序规则;reverse 参数指定以升序(False,默认)还是降序(True)进行排序。sorted() 函数会返回一个排好序的列表。
注意,key 参数和 reverse 参数是可选参数,即可以使用,也可以忽略。
下面程序演示了 sorted() 函数的基本用法:
#对列表进行排序 a = [5,3,4,2,1] print(sorted(a)) #对元组进行排序 a = (5,4,3,1,2) print(sorted(a)) #字典默认按照key进行排序 a = {4:1,/ 5:2,/ 3:3,/ 2:6,/ 1:8} print(sorted(a.items())) #对集合进行排序 a = {1,5,3,2,4} print(sorted(a)) #对字符串进行排序 a = "51423" print(sorted(a))
程序执行结果为:
[1, 2, 3, 4, 5]
[1, 2, 3, 4, 5]
[(1, 8), (2, 6), (3, 3), (4, 1), (5, 2)]
[1, 2, 3, 4, 5]
['1', '2', '3', '4', '5']
再次强调,使用 sorted() 函数对序列进行排序, 并不会在原序列的基础进行修改,而是会重新生成一个排好序的列表。例如:
#对列表进行排序 a = [5,3,4,2,1] print(sorted(a)) #再次输出原来的列表 a print(a)
程序执行结果为:
[1, 2, 3, 4, 5]
[5, 3, 4, 2, 1]
显然,sorted() 函数不会改变所传入的序列,而是返回一个新的、排序好的列表。
除此之外,sorted()函数默认对序列中元素进行升序排序,通过手动将其 reverse 参数值改为 True,可实现降序排序。例如:
#对列表进行排序 a = [5,3,4,2,1] print(sorted(a,reverse=True))
程序执行结果为:
[5, 4, 3, 2, 1]
另外在调用 sorted() 函数时,还可传入一个 key 参数,它可以接受一个函数,该函数的功能是指定 sorted() 函数按照什么标准进行排序。例如:
chars=['http://c.biancheng.net',/ 'http://c.biancheng.net/python/',/ 'http://c.biancheng.net/shell/',/ 'http://c.biancheng.net/java/',/ 'http://c.biancheng.net/golang/'] #默认排序 print(sorted(chars)) #自定义按照字符串长度排序 print(sorted(chars,key=lambda x:len(x)))
程序执行结果为:
['http://c.biancheng.net',
'http://c.biancheng.net/golang/',
'http://c.biancheng.net/java/',
'http://c.biancheng.net/python/',
'http://c.biancheng.net/shell/']
['http://c.biancheng.net',
'http://c.biancheng.net/java/',
'http://c.biancheng.net/shell/',
'http://c.biancheng.net/python/',
'http://c.biancheng.net/golang/']
此程序中,使用了 lambda 表示式,其用法会在后续章节进行详细介绍。
相关文章
- python之open函数
- Python-正则匹配
- python strip()函数
- Python_note_003(Python中的输入函数input()、运算符用法)「建议收藏」
- python 中进制转换及format(),int()函数用法「建议收藏」
- python format()函数的用法
- python基础(7)内置函数divmod用法
- 【说站】python函数符号sympy的用法
- 【说站】python函数的理解及定义
- 【说站】python sorted()函数的参数用法
- python 流程、循环、异常、函数的高级用法(3.0)
- pandas的columns函数_python value_counts
- python学习:map函数和filter函数用法教程
- Python常看函数用法,返回值类型
- python chmod_Python os.chmod用法及代码示例
- python定义函数求和_Python定义函数实现累计求和操作
- Python基础语法-函数的高级用法-闭包
- Python函数(函数定义、函数调用)用法详解
- 一组python用于验证数据的函数详解编程语言
- Python学习:6.python内置函数详解编程语言
- python的re模块详解编程语言
- 提升Linux环境:升级Python(linux升级python)
- 使用 Python 函数进行模块化
- Python中int()函数的用法
- Python中用format函数格式化字符串的用法
- Python基础之函数用法实例详解