Python:在列表中找到函数返回最小值的项目?

编程入门 行业动态 更新时间:2024-10-27 08:29:44
本文介绍了Python:在列表中找到函数返回最小值的项目?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有一个包含坐标的点列表和另一个点.

I've a list of point with coordinates and another point.

列表中的示例:

(45.1531912,5.7184742),(45.1531912,5.7184742),(45.1531113,5.7184544),(45.1525337,5.718298),(45.1525337,5.718298),

一点:

(45.1533837,5.7185242)

一个功能:

def dist(point1,point2) .... return aDistance

是否有一个python内衬(list-comprehension?)在列表中找到一个点,给定函数在该点上返回列表的最小值?

Is there a python one liner (list-comprehension ?) to find a point in the list where a given function returns the minimal value for the list ?

推荐答案

min()函数已经接受了key参数,无需列表理解.

The min() function takes a key argument already, no need for a list comprehension.

假设您要在列表中找到最接近原点的点:

Let's say you wanted to find the closest point in the list to the origin:

min(list_of_points, key=lambda p: distance(p, (0, 0)))

将找到它(给定一个distance()函数来计算两点之间的距离).

would find it (given a distance() function that calculates the distance between two points).

从文档中:

可选的 key 参数指定一个与list.sort()相同的单参数排序函数.如果提供了key参数,则必须采用关键字形式(例如min(a,b,c,key=func)).

The optional key argument specifies a one-argument ordering function like that used for list.sort(). The key argument, if supplied, must be in keyword form (for example, min(a,b,c,key=func)).

更多推荐

Python:在列表中找到函数返回最小值的项目?

本文发布于:2023-11-03 07:39:17,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1554595.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:函数   最小值   项目   列表中   Python

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!