首页 > 解决方案 > 列表排序在 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

标签: python

解决方案


您只需要将列表 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


推荐阅读