查找文件中的最小浮点,然后在其上打印并在其上面一行 [英] Finding smallest float in file then printing that and line above it

查看:50
本文介绍了查找文件中的最小浮点,然后在其上打印并在其上面一行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的数据文件如下:

3.6-band 
6238
Over
0.5678
Over
0.6874
Over
0.7680
Over
0.7834

我想要做的是挑选出最小的浮点数和直接在其上方的单词,并打印出这两个值.我不知道我在做什么.我已经尝试过

What I want to do is to pick out the smallest float and the word directly above it and print those two values. I have no idea what I'm doing. I've tried

df=open('filepath')
  for line in df:
    df1=line.split()
    df2=min(df1)

至少我试图隔离最小的浮点数.问题在于,这只是给我最后的价值.我认为这是python的一个问题,它不知道从迭代开始,但又...不知道我在做什么.我尝试df2=min(df1.seek(0))失败,但出现错误消息no attribute seek.因此,这是到目前为止我尝试过的方法,我仍然不知道如何打印最小浮点数之前的行.谢谢您的建议/帮助/建议.

Which is my attempt at at least trying to isolate the smallest float. Problem is it's just giving me the last value. I think that's a problem with python not knowing to start over with the iteration, but again...no idea what I'm doing. I tried df2=min(df1.seek(0)) with no success, got an error saying no attribute seek. So that's what I've tried so far, I still have no idea how to print the row that would come before the smallest float. Suggestions/help/advice would be appreciated, thanks.

请注意:此数据文件是具有类似特征的较大文件的示例,但是"Over"一词也可能是"Under",这就是为什么我也需要打印该文件.

As a side note: this data file is an example of a larger one with similar characteristics, but the word 'Over' could also be 'Under', that's why I need to have it printed as well.

推荐答案

将项目存储在列表列表中,成对[word,num],然后在该列表列表中应用min.使用minkey参数指定用于比较项目的项目.

Store the items in a list of lists,[word,num] pairs and then apply min on that list of list. Use key parameter of min to specify the which item must be used for comparison of item.:

with open('abc') as f:
    lis = [[line.strip(),next(f).strip()] for line in f]
    minn = min(lis, key = lambda x: float(x[1]))
    print "\n".join(minn)
...     
Over
0.5678

此处lis看起来像这样:

[['3.6-band', '6238'], ['Over', '0.5678'], ['Over', '0.6874'], ['Over', '0.7680'], ['Over', '0.7834']]

这篇关于查找文件中的最小浮点,然后在其上打印并在其上面一行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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