python——sorted()排序函数和round()函数

本文详细介绍Python中sorted()函数的使用方法,包括对不同数据类型如列表、字典、数组和嵌套列表的排序技巧,以及reverse参数的运用实现升序与降序排列。同时,解析round()函数如何对数字进行精确度调整,实现四舍五入。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

sorted()函数:

# sorted()默认为升序排列,reverse=True指定为降序排列
# sorted()函数可以对list,dict,array,tuple进行排序
# 例子:
# (1)排序字符串列表
# scores = ['A', 'B', 'C', 'D']
# scores = sorted(scores, reverse=True)
# 得:['D', 'C', 'B', 'A']
# (2)排序字典
# 按照关键字来排序
# scores = {'A': 3, 'B': 2, 'C': 1}
# scores = sorted(scores, reverse=True)
# 得:['C', 'B', 'A']
# (3)排序数组
# 一维数组排序跟列表一样
# 多维数组排序按照每一行的首元素来排序
# (4)嵌套列表
# 不管是列表中嵌套元组还是列表中嵌套列表,都按照列表中每个元素的首元素来排序
# 即sorted可以实现元组间和列表间排序,但不能实现在字典间排序
# scores = [(0, 5), (1, 4), (2, 3)]
# scores = sorted(scores, reverse=True)
# 得:[(2,3), (1, 4), (0, 5)]

# scores = [[1, 9, 7], [3, 5, 8], [2, 10, 5]]
# scores = sorted(scores, reverse=True)
# 得:[[3, 5, 8], [2, 10, 5], [1, 9, 7]]

round()函数:

# round(number, ndigits)表示将number转换为指定精度的数字,ndigits表示精度的位数。
# 如果number本身的精度小于指定的精度则返回它本身。
# 比如:round(5.2, 2)返回5.2
# 如果number本身的精度大于指定的精度则将number变为指定的精度返回,并且进行四舍五入。
# 比如:round(5.2056, 2)返回5.21,进行了四舍五入。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值