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

标签 python del

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/

相关文章:

python - Perl 中有类似 Python Itertools 的东西吗?

python - PyOpenGL.glDeleteBuffers 在 __del__ 函数中的奇怪行为?

javascript - 在 Laravel Mix 中删除临时文件

python - 将一个元素追加到列表中,并在追加后经过特定时间后删除/弹出/删除它

python - 制作 pacman 游戏,但不知道如何在碰撞后移除 pac 颗粒

要列出的字符串内的 Python 列表

python - UUIDField 的 'default' 属性是否处理唯一性?

python - IE 和 Chrome 无法使用 Selenium2 Python

python - NetworkX 打乱节点顺序

python - python,del或delattr哪个更好?