繁体   English   中英

将文本文件排序到每个新行的列表中,找到最大值并打印它所在的行号

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM