[英]Find the smallest float in a file and printing the line
I have a data file like this: 我有一个这样的数据文件:
1 13.4545
2 10.5578
3 12.5578
4 5.224
I am trying to find the line with the smallest float number and print or write the entire line (including the integer) to another file. 我试图找到具有最小浮点数的行,然后打印或将整行(包括整数)写入另一个文件。 so i get this:
所以我得到这个:
4 5.224
I have this but does not work: 我有这个,但是不起作用:
with open(file) as f:
small = map(float, line)
mini = min(small)
print mini
also tried using this: 也尝试使用此:
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
Using your data file, we can iterate over each line of the file inside min
since min
takes an iterator: 使用您的数据文件,我们可以在
min
内迭代文件的每一行,因为min
需要一个迭代器:
>>> with open(fn) as f:
... print min(f)
...
1 13.4545
Obviously, that is using the ascii value of the integer for determining min. 显然,这是使用整数的ascii值确定最小值的。
Python's min takes a key function: Python的min具有关键功能:
def kf(s):
return float(s.split()[1])
with open(fn) as f:
print min(f, key=kf)
Or: 要么:
>>> with open(fn) as f:
... print min(f, key=lambda line: float(line.split()[1]))
...
4 5.224
The advantage (in both versions) is that the file is processed line by line -- no need to read the entire file into memory. 优点(在两个版本中)是逐行处理文件-无需将整个文件读入内存。
The entire line is printed but only the float part is used to determine the min value of that line. 将打印整行,但仅使用浮点部分确定该行的最小值。
To fix YOUR version, the issue is your first list comprehension. 要修复您的版本,问题是您首先要了解列表。 Your version has
next()
in it which you probably thought was the next number. 您的版本中包含
next()
,您可能认为是下一个数字。 It isn't: It is the next line: 不是:是下一行:
>>> 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']]
The first list comprehension should be: 第一列表理解应为:
>>> 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']]
Then the rest will work OK (but you will have the split list in this case -- not the line -- to print): 然后其余的就可以正常工作(但在这种情况下,您将有拆分列表(不是行)要打印):
>>> minimum=min(mylist, key = lambda x: float(x[1]))
>>> minimum
['4', '5.224']
You were quite near, this is the minimal edit needed 您就在附近,这是所需的最少编辑
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: 地图:
map(function, iterable, ...) Apply function to every item of iterable and return a list of the results. map(function,iterable,...)将函数应用于iterable的每个项目,并返回结果列表。 Link
链接
Demo: 演示:
>>> 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
and small_row
variables to None. small
和small_row
变量设置为None。 Demo: 演示:
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
Output: 输出:
$ python 3.py
small_row: ['4', '5.224']
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.