簡體   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