列表排序在python 3.7中出现故障

时间:2019-05-14 11:03:10

标签: python

我是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

3 个答案:

答案 0 :(得分:3)

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

答案 1 :(得分:1)

这是因为您正在比较str

请从str更改为int

# 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)
intList=[]
for char in z:
    intList.append(int(char))
print(intList)
intList.sort(reverse=True)
print(intList)

答案 2 :(得分:0)

其他解决方案也可以。但是,如果出于某种原因希望保留z字符串列表,则可以在排序算法中对其进行转换。

在您的代码中,将key添加到sort方法中:

z.sort(key=int, reverse=True)

仅在排序过程中,字符串才会转换为数字。