[英]Sorting text file into lists of every new line, finding the biggest value and printing the number of the line in which it is
這是我第一次在這里尋求幫助,但肯定不會持續很久,因為我只是一個苦苦掙扎的初學者。
我有一個帶有一些數字的文本文件,例如。 :
5 26 83 1 5645
7 3758 69 4 84
我想將這些行排序到列表中,我已經部分完成了這行代碼: result = [line.split(" ") for line in file.readlines()]
-不確定這是否是正確的方法它是為了使用它,但也許我會在這里找到一些幫助
現在,當我將文本文件的每一行分隔為一個值列表時,我想在整個文本文件中找到最高值並找到數字在哪一行。 -我可以用“max”方法找到最高值,但僅此而已
例如,在 20 行數字中,最高值為“94515”,位於第 13 行。
這就是我想要完成的。
嘗試這個:
with open('path/to/file', 'r') as file:
result = [list(map(int, line.split())) for line in file.readlines() if line.strip()]
max_int = max(j for i in result for j in i)
line_nums = [i+1 for i, j in enumerate(result) if max_int in j]
逐行處理:
with open('data.txt', 'r') as file:
imax, max_line = float('-inf'), -1 # init of overall max and line number
for line_no, line in enumerate(file):
# Use try/except to ignore problem lines (such as blank line)
try:
line_max = max(map(int, line.rstrip().split())) # max in line
# Line above does the following:
# line.strip() remove "/n" at end of line
# .split() convert string into list of numbers
# (e.g. "1 2 3".split() -> ['1', '2', '3']
# map(int, lst) converts list of strings into numbers
# (i.e. ['1', '2', '3'] -> [1, 2, 3]
# max takes the max of the numbers in the list
if line_max > imax:
imax, max_line = line_max, line_no # update overall max
except:
continue # ignores problems (such as blank lines)
print(f'Max {imax} on line {max_line}')
測試
data.txt 文件內容(第三行空白)
5 26 83 1 5645
7 3758 69 4 84
17 8 19 21 15
232 231 99999 15
輸出(輸出最大值和行號)
Max 99999 on line 4
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.