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

标签 python

我的代码都有效,列表也有效,但出于某种原因,当我尝试对其进行排序时,列表没有按升序排序,而是随机排序。因此,虽然列表发生变化,但它不会按降序排序。当我尝试 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/

相关文章:

python - RdKit 分子中原子的坐标

python - 全局名称 'key' 未定义

python - 使用 Sqlite 将自动递增 ID 列添加到现有表

python - 当选择和更新都存在复杂条件时,更新数据框的最快方法是什么?

python - 如何使用 python 提取 exe-archive 的内容?

Python-替换字典中键、值中的特殊字符

python - 对公司名称的 DataFrame 进行非规范化 [第 1 部分]

python - 在虚拟环境中使用 pip 构建 uwsgi 时出错

python - 如何根据 flask 中的测试和生产环境分配设置?

python - 如何根据PANDAS中的groupby字段在for循环中写入to_excel动态文件名?