由于 [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
, j
used 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.
相关推荐
最新文章