[英]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.