python - 列表排序在 python 3.7 中出现故障
问题描述
我是 python 新手,我正在练习编写代码来计算 CDF(累积密度函数),代码如下:
它工作正常,除非在某些情况下我输入类似:12-12-125-15-152-16-10
反向排序没有得到正确的排序结果。
# This is a trial to make an app for calculating the CDF for a set of numbers
# x = int(input("Please Enter the Number of Samples: ")) # x represents the number of samples
y = input("\nPlease Enter the samples separated by (-) with no spaces: ") # y represents the samples collection point
# print(y)
z = y.split("-")
x = len(z)
s = len(z)+1 # s represents the total sample space
print("\nThe number of samples is {} and the sample space is {} sample.\n".format(x,s))
# z.reverse()
z.sort(reverse=True)
# print(z)
# print(len(z))
ind = 0
for i in z:
ind+= 1
freq = (ind)/s
print(i, freq, ind)
预期排序结果:152 125 16 15 12 12 10
实际排序结果:16 152 15 125 12 12 10
解决方案
您只需要将列表 Z 中的 str 转换为 int:可能的解决方案是添加list(map(int, z))
# This is a trial to make an app for calculating the CDF for a set of numbers
# x = int(input("Please Enter the Number of Samples: ")) # x represents the number of samples
y = input("\nPlease Enter the samples separated by (-) with no spaces: ") # y represents the samples collection point
# print(y)
z = y.split("-")
z = list(map(int, z))
x = len(z)
s = len(z)+1 # s represents the total sample space
print("\nThe number of samples is {} and the sample space is {} sample.\n".format(x,s))
# z.reverse()
z.sort(reverse=True)
# print(z)
# print(len(z))
ind = 0
for i in z:
ind+= 1
freq = (ind)/s
print(i, freq, ind)
那么结果是:152 125 16 15 12 12 10
推荐阅读
- asp.net - 如何使用asp.net mvc为facebook或其他社交媒体网站设置cookie过期时间?
- hibernate - Hibernate envers :: 使用 AuditReader 从审计表中获取关联实体(具有一对多关系)的方法是什么?
- unity3d - 当 eulerangles 为 180 时,Unity 2D Shotgun 射击不起作用
- bash - 使用双引号传递变量内容
- python - 根据其他列的值作为组设置列中的值
- c# - 如何从 NodeJS/ElectronJS 调用 C++/C# 代码与 DLL 交互?
- reactjs - 使用 GitHub 操作部署反应应用程序的问题
- embedded - 如何为 IAR 工作台设置深色主题
- laravel - 如何在 laravel 中使用`whereDoesntHave`
- dask - 使用客户端扩展作业队列集群