如何从python文本文件中删除数字最大的行?

2024-10-02 22:30:40 发布

您现在位置:Python中文网/ 问答频道 /正文

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))

但这并不总是能选出前五名,而且往往是随机挑选出来的。请帮帮我!你知道吗


Tags: 代码txtdataaswith变体openmax
2条回答

试试这个:

from contextlib import closing

with closing(open('winners.txt', 'r')) as file:
    gone = max(map(lambda x: x.rstrip('\n'), file.readlines()))

print(gone)

下面是一个简单的解决方案:

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)

相关问题 更多 >