亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

排序后如何從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 關注
  • 122 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號