2013-01-13 131 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) 
相关问题