Finding smallest float in file then printing that and line above it

前端 未结 5 1090
离开以前
离开以前 2020-11-29 14:16

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

5条回答
  •  野趣味
    野趣味 (楼主)
    2020-11-29 14:42

    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
    

    Here lis looks like this:

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

提交回复
热议问题