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]
添加回答
举报
