在文件中找到最小的浮点数,然后在其上方打印该行 [英] Finding smallest float in file then printing that and line above it
问题描述
我的数据文件如下所示:
My data file looks like this:
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
在那个名单上.使用 min
的 key
参数来指定必须使用哪个 item 来比较 item.:
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 "
".join(minn)
...
Over
0.5678
这里的 lis
看起来像这样:
Here lis
looks like this:
[['3.6-band', '6238'], ['Over', '0.5678'], ['Over', '0.6874'], ['Over', '0.7680'], ['Over', '0.7834']]
这篇关于在文件中找到最小的浮点数,然后在其上方打印该行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!