【问题标题】:How can I get the element of a list that has a minimum/maximum property in Python?如何在 Python 中获取具有最小/最大属性的列表元素?
【发布时间】:2010-11-30 10:30:19
【问题描述】:

我在 Python 中有以下数组:

points_list = [point0, point1, point2]

其中每个points_list 的类型为:

class point:
    __init__(self, coord, value):
        self.coord = numpy.array(coord)
        self.value = value
# etc...

还有一个功能:

def distance(x,y):
    return numpy.linalg.norm(x.coord - y.coord)

我在别处定义了一个观点point_a。现在我想在points_list 中找到最接近point_a 的点。

除了循环,在 Python 中最好的方法是什么?

【问题讨论】:

    标签: python list


    【解决方案1】:

    你试过了吗?

    min(points_list, key=lambda x: distance(x, point_a))
    

    在评论中回答问题lambda 在这里确实是必要的,因为function specified as a key argument needs to accept only a single argument

    然而,由于您的 point_a 本质上是全局的,您可以将其“硬编码”到 distance 函数中:

    >>> point_a = point([1, 2, 3], 5)
    >>> def distance(x):
        return numpy.linalg.norm(x.coord - point_a.coord)
    

    这样您可以将distance 作为关键参数传递,完全跳过lambda

    >>> min(points_list, key=distance)
    

    【讨论】:

    • 另一个我不知道的 Python 函数 :) +1。我想只有当您打算同时计算最小值和最大值时,循环才会有益。
    • @Andre:我认为更好的选择是使用 sort 和相同的 key 参数并获取第一个和最后一个元素。
    • @SilentGhost:好吧..也许你想要最小值、最大值和平均值:-)
    • 你还在循环,你只需要 min() 为你做。
    • 我不知道min() 接受key 参数。谢谢。
    猜你喜欢
    • 1970-01-01
    • 2011-07-04
    • 1970-01-01
    • 2018-04-21
    • 1970-01-01
    • 2017-09-20
    • 2013-09-28
    • 2014-06-09
    • 1970-01-01
    相关资源
    最近更新 更多