試圖找到最好和最簡單的方法來列出 150G 文本文件中的前 5 個數字。我正在搜索的文件每行中只有數字,如下所示。45678987609876536489874509876...嘗試了下面的程序,它仍然只顯示數字中的第一個數字,而不是完整的數字。from heapq import nlargestdata=open('number.txt','r')text=data.read()print (text)print nlargest(5, (text))data.close()還有其他方法可以選擇前5名嗎?
2 回答

慕仙森
TA貢獻1827條經驗 獲得超8個贊
輸入:
456789876
098765
36
48987
4509876
563456
47345734
6234
67456
235423
7348
3
656
代碼:
data=open('number.txt','r')
text=data.readlines()#read the file line to line and introduce in a list of string
numbers = map(int, text)#convert the list of string in list of int
numbers.sort()#sort your list
print (numbers[-5:])#print the 5 largest
print (numbers[:5])#print the 5 smaller
結果:
[235423, 563456, 4509876, 47345734, 456789876]
[3, 36, 656, 6234, 7348]
添加回答
舉報
0/150
提交
取消