[英]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
使用您的数据文件,我们可以在min
内迭代文件的每一行,因为min
需要一个迭代器:
>>> with open(fn) as f:
... print min(f)
...
1 13.4545
显然,这是使用整数的ascii值确定最小值的。
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']
您就在附近,这是所需的最少编辑
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/
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
地图:
map(function,iterable,...)将函数应用于iterable的每个项目,并返回结果列表。 链接
演示:
>>> 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
变量设置为None。 演示:
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']
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.