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

我有一个项目需要我对数字进行排序,但这很好,直到数字 113 我也不知道如何排序超过 100


scoresdoc = 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 的数字不会出现`


郎朗坤
浏览 151回答 1
1回答

白板的微信

您可以尝试以下实现。代码: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:245356632345633424561112222222344输出:>>> python3 test.pyTop 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_excint_list.sort(reverse=True)print("\nTop Five Scores:\n")print(int_list[0:5])测试.txt:2453asdf5663dsfa189输出:>>> python3 test.pyWrong value: asdfWrong value: dsfaTop Five Scores:[189, 56, 45, 6, 3]
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python