试图找到最好和最简单的方法来列出 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
提交
取消
