我的代码都有效,列表也有效,但出于某种原因,当我尝试对其进行排序时,列表没有按升序排序,而是随机排序。因此,虽然列表发生变化,但它不会按降序排序。当我尝试 x.sort(reverse=True) 时弹出一条错误消息,说它不能是整数形式。 谁能帮我?
score=input('What is your score?')
Scorefile=open('score.txt','a')
Scorefile.write(score)
Scorefile.write("\n")
Scorefile.close()
Scorefile = open('score.txt','r')
with open('score.txt','r') as Scorefile:
scores=Scorefile.readline()
List=[]
while scores:
scores2=(scores.strip())
int(scores2)
List.append(scores2)
scores=Scorefile.readline()
List.sort()
print(List)
#Output(not in ascending order)
['12', '12', '12', '12', '12', '13', '15', '17', '4', '5', '6']
最佳答案
您的元素是字符串(str
类型),而不是整数(int
类型)。您的代码目前似乎按词典顺序排序。
尝试在排序前将您的元素转换为 int
。更改代码中的这些行:
int(scores2)
List.append(scores2)
为此:
List.append(int(scores2))
int(scores2)
单独一行没有任何用处,您必须使用 int()
的输出。
关于python - 为什么我的排序功能不能正常工作?(Python),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58311589/