我有一个这样的数据文件:
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
答案 0 :(得分:4)
使用您的数据文件,我们可以迭代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']
答案 1 :(得分:2)
你很近,这是所需的最小编辑
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/
答案 2 :(得分:0)
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
答案 3 :(得分:0)
<强>图:强>
map(function,iterable,...) 将函数应用于iterable的每个项目并返回结果列表。 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: .
>>>
small
和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']