为了账号安全,请及时绑定邮箱和手机立即绑定

排序后如何从python中的文本文件中显示超过100的数字?

排序后如何从python中的文本文件中显示超过100的数字?

郎朗坤 2022-05-24 15:55:54
我有一个项目需要我对数字进行排序,但这很好,直到数字 113 我也不知道如何排序超过 100scoresdoc = open("scoresdoc.txt","r+")lines2 = scoresdoc.read()x = lines2.split()x.sort(reverse=True)print("\nTop Five Scores:\n")print(x[0:5])scoresdoc.close()该代码目前工作正常,但不适用于超过 100 的数字,这是一个问题,预期是前五名,但超过 100 的数字不会出现`
查看完整描述

1 回答

?
白板的微信

TA贡献1883条经验 获得超3个赞

您可以尝试以下实现。


代码:


with open("test.txt", "r") as opened_file:

    lines = opened_file.readlines()

lines = list(map(int, lines))

lines.sort(reverse=True)

print("\nTop Five Scores:\n")

print(lines[0:5])

测试.txt:


2

45

3

56

6

3

2

34

5

63

3

42

45

6

1

112

22222

2

34

4

输出:


>>> python3 test.py


Top Five Scores:


[22222, 112, 63, 56, 45]

编辑:


如果您有无法转换为整数的元素,则可以使用以下实现:


代码:


with open("test.txt", "r") as opened_file:

    lines = opened_file.readlines()

int_list = []

for elem in lines:

    try:

        int_list.append(int(elem))

    except ValueError:

        print("Wrong value: {}".format(elem))

    except Exception as unexp_exc:

        print("Unexcepted error: {}".format(unexp_exc))

        raise unexp_exc

int_list.sort(reverse=True)

print("\nTop Five Scores:\n")

print(int_list[0:5])

测试.txt:


2

45

3

asdf

56

6

3

dsfa

189

输出:


>>> python3 test.py

Wrong value: asdf


Wrong value: dsfa



Top Five Scores:


[189, 56, 45, 6, 3]


查看完整回答
反对 回复 2022-05-24
  • 1 回答
  • 0 关注
  • 150 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号