繁体   English   中英

为什么我的排序 function 不能正常工作?(Python)

[英]Why does my sort function not work properly?(Python)

我的代码一切正常,列表工作,但由于某种原因,当我尝试对其进行排序时,列表不会按升序排序,而是按随机顺序排序。因此,当列表更改时,它不会按降序排序。 当我尝试 x.sort(reverse=True) 时,弹出一条错误消息,说它不能采用 integer 形式。 谁能帮我?

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()的 output 。

它不是对数字进行排序,而是对字符串进行排序。 作为字符串,它们被排序。

您可以通过更改此行来解决此问题

        int(scores2)

对此。

        scores2 = int(scores2)

现在,您正在将该值转换为 integer,但实际上并未在任何地方使用该 integer。 我认为这就是混乱的来源。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM