繁体   English   中英

Python查找列表项函数的最小值,但返回列表项

[英]Python finding minimum values of functions of list items, but returning the list item

对不起,在标题中解释我的问题有点困难,但基本上,我有一个职位列表,每个职位都可以通过一个函数来获取一个数字,为​​你提供有关职位的数据。 我想要做的是返回列表中具有最低数据值的位置,但我似乎找不到这样做的方法。

一些伪代码应该有所帮助:

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

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

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 ,我认为大致相同,但更具可读性。

你基本上可以使用min()函数

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

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

min(pos, key=posfunc)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM