Tre*_*sin 2 python list minimum
对不起,在标题中解释我的问题有点困难,但基本上,我有一个职位列表,每个职位都可以通过一个函数来获取一个数字,为你提供有关职位的数据.我想要做的是返回列表中具有最低数据值的位置,但我似乎找不到这样做的方法.
一些伪代码应该有所帮助:
def posfunc(self,pos):
x,y = pos
return x**2-y
def minpos(self)
returns position with the least x**2-y value
Run Code Online (Sandbox Code Playgroud)
Python非常酷:D:
min(positions, key=posfunc)
Run Code Online (Sandbox Code Playgroud)
从内置文档:
>>> 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.
Run Code Online (Sandbox Code Playgroud)
lambda值得一提:
min(positions, key=lambda x: x[0]**2 - x[1])
Run Code Online (Sandbox Code Playgroud)
如果您没有posfunc在其他地方使用,我认为大致相同,但更具可读性.
| 归档时间: |
|
| 查看次数: |
2534 次 |
| 最近记录: |