with open('winnernum.txt', 'r') as b:
data = b.readlines()
gone=(max(data))
print(gone)
with open("winnernum.txt","r") as h:
del gone
我已经在 python 中尝试过此代码以及此代码的其他变体,但它仍然无法删除。我需要从文本文件中打印前 5 个最大的数字。
我之前尝试过使用这个:
with open('winners.txt', 'r') as b:
data = b.readlines()
gone=(max(data))
print(gone)
import heapq
print(heapq.nlargest(5, winner))
但这并不总是选择前 5 个数字,而是倾向于随机选择它们。请帮忙!
最佳答案
这是一个简单的解决方案:
from heapq import nlargest
with open("winnernum.txt", "r") as f:
numbers = [float(line.rstrip()) for line in f.readlines()]
largest = nlargest(5, numbers)
print(largest)
关于python - 如何从文本文件python中删除最大数字的行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59503448/