python3浮点数排序

python2有很多浮点数排序的方式,可是python3的sort函数中没有cmp参数了十分不方便,下面列出几种python3适合的浮点数排序方法
原文地址Python | Ways to sort list of float values

方法一:lambda表达式

# 浮点数排序

# 列表初始化
Input = [12.8, .178, 1.8, 782.7, 99.8, 8.7] 

# 用lambda进行排序
Output = sorted(Input, key = lambda x:float(x)) 

# 打印输出
print(Output)

方法二:使用排序方法sorted

# 列表初始化
Input = [12.8, .178, 1.8, 782.7, 99.8, 8.7] 

# 使用sorted+key
Output = sorted(Input, key = float) 

# 打印输出
print(Output) 

方法三:使用sort

# Python code to sort list of decimal values 

# 列表初始化
Input = [12.8, .178, 1.8, 782.7, 99.8, 8.7] 

# 使用sort+key
Input.sort(key = float) 

# 打印输出
print(Input) 

以上就是python3浮点数运算的常见方式啦,感谢原文作者的分享。

猜你喜欢

转载自blog.csdn.net/weixin_42474261/article/details/104852271