python 3.7中的列表排序出现故障
我是python新手,我正在练习编写一些代码来计算CDF累积密度函数,代码如下: 它工作正常,但在某些情况下,当我输入以下内容时除外: 12-12-125-15-152-16-10 反向排序无法获得正确的排序结果python 3.7中的列表排序出现故障,python,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 rep
# 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
十,
实际分拣结果:
16
152
15
125
12
12
10您只需将列表Z中的str转换为int: 可能的解决方案是添加listmapint,z
结果是:152 125 16 15 12 10您只需要将str转换为列表Z中的int: 可能的解决方案是添加listmapint,z
结果是:152 125 16 15 12 10这是因为你在比较STR 请把str改成int
这是因为你在比较STR 请把str改成int
其他解决方案也不错。但是,如果出于某种原因希望保留一个z字符串列表,可以在排序算法中转换它们 在代码中,向排序方法添加一个键:
字符串将仅在排序过程中转换为数字。其他解决方案也可以。但是,如果出于某种原因希望保留一个z字符串列表,可以在排序算法中转换它们 在代码中,向排序方法添加一个键:
字符串将仅在排序过程中转换为数字。您正在对字符串进行排序,16实际上大于152。也许你想对数字进行排序?如果是这样,您必须转换为数字。您正在对字符串进行排序,16实际上大于152。也许你想对数字进行排序?如果是这样,你必须转换成数字。感谢罗伯特,这很有帮助!!感谢罗伯特,这很有帮助!!
# 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)
# 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)
z.sort(key=int, reverse=True)