在文件中找到最小的浮点数并打印行

Find the smallest float in a file and printing the line

我有这样一个数据文件:

1 13.4545
2 10.5578
3 12.5578
4 5.224

我试图找到具有最小浮点数的行并将整行(包括整数)打印或写入另一个文件。所以我明白了:

4 5.224

我有这个但是不起作用:

with open(file) as f:
    small = map(float, line)
    mini = min(small)
    print mini

也尝试过使用这个:

with open(file) as f:
    mylist = [[line.strip(),next(f).strip()] for line in f]
    minimum = min(mylist, key = lambda x: float(x[1]))
    print minimum
a=open('d.txt','r')

d=a.readlines()
m=float(d[0].split()[1])

for x in d[1:]:
    if float(x.split()[1])<m:
        m=float(x.split()[1])

print m

你离得很近,这是需要的最少编辑

with open(fl) as f:                             # don't use file as variable name
    line = [i.strip().split() for i in f]       # Get the lines as separate line no and value
    line = [(x[0],float(x[1])) for x in line]   # Convert the second value in the file to float
    m = min(line,key =  lambda x:x[1])          # find the minimum float value, that is the minimum second argument.
    print "{} {}".format(m[0],m[1])             # print it. Hip Hip Hurray \o/

使用您的数据文件,我们可以遍历 min 中文件的每一行,因为 min 使用迭代器:

>>> with open(fn) as f:
...    print min(f)
... 
1 13.4545

很明显,就是用整数的ascii值来确定min。

Python的min取一个关键函数:

def kf(s):
    return float(s.split()[1])

with open(fn) as f:
    print min(f, key=kf)

或者:

>>> with open(fn) as f:
...    print min(f, key=lambda line: float(line.split()[1]))
... 
4 5.224

优点(在两个版本中)是逐行处理文件——无需将整个文件读入内存。

打印整行,但仅浮点部分用于确定该行的最小值。


要修复您的版本,问题是您的第一个列表理解。您的版本中有 next(),您可能认为这是下一个数字。它不是:它是下一行:

>>> with open(fn) as f:
...      mylist = [[line.strip(),next(f).strip()] for line in f]
... 
>>> mylist
[['1 13.4545', '2 10.5578'], ['3 12.5578', '4 5.224']]

第一个列表理解应该是:

>>> with open(fn) as f:
...    mylist=[line.split() for line in f]
... 
>>> mylist
[['1', '13.4545'], ['2', '10.5578'], ['3', '12.5578'], ['4', '5.224']]

然后剩下的就可以正常工作了(但在这种情况下你将得到拆分列表——而不是要打印的行):

>>> minimum=min(mylist, key = lambda x: float(x[1]))
>>> minimum
['4', '5.224']

地图:

map(函数,可迭代的,...) 将函数应用于可迭代的每个项目和 return 结果列表。 Link

演示:

>>> map(float , ["1.9", "2.0", "3"])
[1.9, 2.0, 3.0]

>>> map(float , "1.9")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: could not convert string to float: .
>>> 

  1. 由于输入文件的结构是固定的,所以通过csv模块读取输入文件。
  2. smallsmall_row 变量设置为 None。
  3. 逐行读取文件。
  4. 行中第二项的类型转换,从字符串到浮点数。
  5. 检查小变量 None 或小于行的第二项。
  6. 如果是,则分别分配小值和small_row

演示:

import csv

file1 = "1_d.txt"

small = None
small_row = None
with open(file1) as fp:
    root = csv.reader(fp, delimiter=' ')
    for row in root:
        item = float(row[1])
        if small==None or small>item:
            small = item
            small_row = row

print "small_row:", small_row

输出:

$ python 3.py 
small_row: ['4', '5.224']