python - 提取不同行中最大数的索引
问题描述
我正在编写用于从文件中提取特定行的代码,然后查找最大数量,更具体地说是其位置(索引)。所以我开始我的代码寻找这些行:
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 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
推荐阅读
- python - Mac 终端上的 Python - 被杀:9
- r - 如何向回归表添加额外的 GOF,例如 ivreg 诊断?
- c# - 使用 MS Excel VSTO 插件如何抑制标准 Excel 的“另存为”功能并显示自定义窗口进行保存?
- spring-data-jpa - 具有多个实体的 Spring Data Repository
- python - 如何在 Cog Discord.Py 重写中正确定义“客户端”
- javascript - 添加 firestore 文档返回“时间戳不是构造函数”
- mysql - Mysql2::Error::ConnectionError: Can't connect to local MySQL server through socket '/tmp/mysql.sock' (2)
- c++ - 打印未知结构的所有元素的值
- r - Rmarkdown,将标题字体绘制为拉丁现代
- mysql - 计算 2 个值之间的百分比(总和)