【问题标题】:Python finding minimum values of functions of list items, but returning the list itemPython查找列表项函数的最小值,但返回列表项
【发布时间】:2012-12-27 15:10:15
【问题描述】:

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

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

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

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

【问题讨论】:

    标签: python list minimum


    【解决方案1】:

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

    【讨论】:

    • 还有一个问题,posfunc 是一个方法(以self 为参数)会导致错误吗?
    • 谢谢,我希望会有这样的东西 :)
    【解决方案2】:

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

    pos = [(234, 4365), (234, 22346), (2342, 674)]
    
    def posfunc(pos):
        x,y = pos
        return x**2-y
    
    min(pos, key=posfunc)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-04-11
      • 1970-01-01
      • 1970-01-01
      • 2021-07-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多