如何从* .txt文件中查找最小值 [英] How to Find Minimum value from *.txt file

查看:81
本文介绍了如何从* .txt文件中查找最小值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有 *.txt 文件,其中包含如下数据:

I have *.txt file, which contains data like this:

...
30 5.882973099631601
31 6.035463584639685
32 6.184276444600495
33 6.3336851616329435
34 6.492617147379082
35 6.683538372963013
36 6.841228384748939
37 6.999432758805214
...

现在,我想找到最小值(第二列),但我想将其与第一列中的值一起显示.因此,在这种情况下,我希望将此行作为最小功能进行打印,并且它应该看起来像这样:

Now I would like to find the minimum value (second column), but I'd like to display it with value from the first column. So in that case I'd like to print this row, as a minimum function and it suppose to look like this:

30 5.882973099631601

我一直在尝试用该代码执行此操作,但是我被卡住了.

I've been trying to do this with that code, but I'm stuck.

 with open('measurements.txt', 'a') as j:
        j.write(str(r))
        j.write(" ")
        j.write(line[24:])
        j.write('\n')
        j.close()

推荐答案

import csv

# preparing data - converting to array
rows = []
with open('sample.txt', mode='r') as infile:
    reader = csv.reader(infile, delimiter=" ")
    for row in reader:  # each row is a list
        rows.append(row)

# lambda function to filter min considering the second column
minimus = min(rows, key=lambda x: float(x[1]))

# done
print(minimus)

这篇关于如何从* .txt文件中查找最小值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆