首页 > 解决方案 > 提取不同行中最大数的索引

问题描述

我正在编写用于从文件中提取特定行的代码,然后查找最大数量,更具体地说是其位置(索引)。所以我开始我的代码寻找这些行:

with open (filename,'r') as f:
        lines = f.readlines()
        for index, line in enumerate(lines):
            if 'a ' in line:
                x=(lines[index])
                print(x)

                

因此,从我的代码中,我得到了我正在寻找的行:

a 3 4 5
a 6 3 2

然后我的其余代码正在寻找数字之间的最大值并打印索引:

y = [float(item) for item in x.split()]
                z=y.index(max(y[1:3]))
                print(z)

现在代码找到两个最大数字的索引(所以第一行是 5,第二行是 6):

3
1

但是我希望我的代码也比较两行之间的数字(所以最大的数字在 3,4,5,6,3,2 之间),以输出行的索引,文件中包含的行在哪里最大数字(例如第 300 行)和第 (1) 行中的位置。你能给我一些可能的解决方案吗?

标签: python

解决方案


您应该遍历每一行并一起跟踪行号以及该行中项目的位置。顺便说一句,您应该使用 python 3.9+ 运行它(因为.startswith()方法。)

with open(filename) as f:
    lines = [line.rstrip() for line in f]

max_ = 0
line_and_position = (0, 0)
for i, line in enumerate(lines):
    if line.startswith('a '):

        # building list of integers for finding the maximum
        list_ = [int(i) for i in line.split()[1:]]
        for item in list_:
            if item > max_:
                max_ = item

                # setting the line number and position in that line
                line_and_position = i, line.find(str(item))

print(f'maximum number {max_} is in line {line_and_position[0] + 1} at index {line_and_position[1]}')

输入 :

a 3 4 5
a 6 3 2
a 1 31 4
b 2 3 2
a 7 1 8

输出:

maximum number 31 is in line 3 at index 4


推荐阅读