簡體   English   中英

你如何從文本文件python中刪除最大數字的行?

[英]how do you delete the line with the biggest number from a text file 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))

但這並不總是選擇前 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)

嘗試這個:

from contextlib import closing

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

print(gone)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM