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]
添加回答
舉報