Python的:对于每一个列表元素应用一个函数在整个名单 [英] Python: For each list element apply a function across the list

查看:924
本文介绍了Python的:对于每一个列表元素应用一个函数在整个名单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于 [1,2,3,4,5] ,我怎么可以这样做

Given [1,2,3,4,5], how can I do something like

1/1, 1/2, 1/3,1/4,1/5, ...., 3/1,3/2,3/3,3/4,3/5,.... 5/1,5/2,5/3,5/4,5/5

我想存储所有结果,找到最小,并返回用于找到最小的两个数字。所以在情况下,我上面已经介绍了,我想回(1,5)

所以基本上我希望做像

每个元素列表 映射在所有元素的一些功能的列表,以Ĵ作为参数 结果存储在一个主列表,找到主列表中的最小值,并返回参数Ĵ用于计算该最小值

for each element i in the list map some function across all elements in the list, taking i and j as parameters store the result in a master list, find the minimum value in the master list, and return the arguments i, jused to calculate this minimum value.

在我的真正的问题我有一个列表对象/坐标,我现在用的函数有两个坐标,计算出欧氏距离。我试图找到任何两点之间的最小欧氏距离,但我并不需要一个花哨的算法。

In my real problem I have a list objects/coordinates, and the function I am using takes two coordinates and calculates the euclidean distance. I'm trying to find minimum euclidean distance between any two points but I don't need a fancy algorithm.

推荐答案

您可以使用的名单COM prehensions 分钟()(Python的3​​.0 code)

You can do this using list comprehensions and min() (Python 3.0 code):

>>> nums = [1,2,3,4,5]
>>> [(x,y) for x in nums for y in nums]
[(1, 1), (1, 2), (1, 3), (1, 4), (1, 5), (2, 1), (2, 2), (2, 3), (2, 4), (2, 5), (3, 1), (3, 2), (3, 3), (3, 4), (3, 5), (4, 1), (4, 2), (4, 3), (4, 4), (4, 5), (5, 1), (5, 2), (5, 3), (5, 4), (5, 5)]
>>> min(_, key=lambda pair: pair[0]/pair[1])
(1, 5)

请注意,要在Python 2.5中运行这个,你需要做任何的参数之一花车,或做从__future__进口师使1/5正确等于0.2,而不是0。

Note that to run this on Python 2.5 you'll need to either make one of the arguments a float, or do from __future__ import division so that 1/5 correctly equals 0.2 instead of 0.

这篇关于Python的:对于每一个列表元素应用一个函数在整个名单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆