2013-01-13 127 views
2

對不起,在標題中解釋我的問題有點困難,但基本上,我有一個位置列表,每個位置都可以通過函數獲取一個數字,爲​​您提供有關位置的數據。我想要做的是返回列表中數據值最低的位置,但我似乎無法找到這樣做的方法。Python找到列表項的最小值,但返回列表項的最小值,但返回列表項

的僞代碼中的位應該有所幫助:

def posfunc(self,pos): 
    x,y = pos 
    return x**2-y 

def minpos(self) 
    returns position with the least x**2-y value 

回答

6

Python是很酷:d:

min(positions, key=posfunc) 

從內置的文檔:

>>> help(min) 
min(...) 
    min(iterable[, key=func]) -> value 
    min(a, b, c, ...[, key=func]) -> value 

    With a single iterable argument, return its smallest item. 
    With two or more arguments, return the smallest argument. 

和lambda的都值得在此提及:

min(positions, key=lambda x: x[0]**2 - x[1]) 

大致相同,但更具可讀性我認爲,如果您不在其他地方使用posfunc

+0

並有問題,會'posfunc'的是一個方法(以'self'作爲參數)造成的錯誤? – utdemir

+0

謝謝,我希望能有這樣的東西:) – Treesin

3

你基本上可以使用MIN()函數

pos = [(234, 4365), (234, 22346), (2342, 674)] 

def posfunc(pos): 
    x,y = pos 
    return x**2-y 

min(pos, key=posfunc) 
相關問題