简体   繁体   English

Python:对于每个列表元素,在列表中应用一个函数

[英]Python: For each list element apply a function across the list

Given [1,2,3,4,5] , how can I do something like 鉴于[1,2,3,4,5] ,我该怎样做

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

I would like to store all the results, find the minimum, and return the two numbers used to find the minimum. 我想存储所有结果,找到最小值,并返回用于找到最小值的两个数字。 So in the case I've described above I would like to return (1,5) . 所以在我上面描述的情况下,我想返回(1,5)

So basically I would like to do something like 所以基本上我想做点什么

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. 对于列表中的每个元素i映射列表中的所有元素的一些函数,将ij作为参数将结果存储在主列表中,在主列表中找到最小值,并返回用于计算的参数ij这个最小值。

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. 我试图找到任意两点之间的最小欧氏距离,但我不需要花哨的算法。

You can do this using list comprehensions and min() (Python 3.0 code): 你可以使用list comprehensionsmin() (Python 3.0代码)来做到这一点:

>>> 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)

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 2.5上运行它,您需要将其中一个参数设置为float,或者from __future__ import division以便1/5正确等于0.2而不是0。

If I'm correct in thinking that you want to find the minimum value of a function for all possible pairs of 2 elements from a list... 如果我认为您想要从列表中找到所有可能的2个元素对的函数的最小值,那是正确的...

l = [1,2,3,4,5]

def f(i,j):
   return i+j 

# Prints min value of f(i,j) along with i and j
print min( (f(i,j),i,j) for i in l for j in l)

Some readable python: 一些可读的python:

def JoeCalimar(l):
    masterList = []
    for i in l:
        for j in l:
            masterList.append(1.*i/j)
    pos = masterList.index(min(masterList))
    a = pos/len(masterList)
    b = pos%len(masterList)
    return (l[a],l[b])

Let me know if something is not clear. 如果有什么不清楚,请告诉我。

If you don't mind importing the numpy package, it has a lot of convenient functionality built in. It's likely to be much more efficient to use their data structures than lists of lists, etc. 如果您不介意导入numpy包,它内置了许多方便的功能。使用它们的数据结构可能比列表列表等更有效。

from __future__ import division

import numpy

data = numpy.asarray([1,2,3,4,5])
dists = data.reshape((1,5)) / data.reshape((5,1))

print dists

which = dists.argmin()
(r,c) = (which // 5, which % 5) # assumes C ordering

# pick whichever is most appropriate for you...
minval = dists[r,c]
minval = dists.min()
minval = dists.ravel()[which]

Doing it the mathy way... 这样做的方式......

nums = [1, 2, 3, 4, 5]
min_combo = (min(nums), max(nums))

Unless, of course, you have negatives in there. 当然,除非你在那里有负面影响。 In that case, this won't work because you actually want the min and max absolute values - the numerator should be close to zero, and the denominator far from it, in either direction. 在这种情况下,这不起作用,因为你实际上想要最小和最大绝对值 - 分子应该接近于零,并且分母在任何一个方向上都远离它。 And double negatives would break it. 而双重否定将打破它。

If working with Python ≥2.6 (including 3.x), you can: 如果使用Python≥2.6(包括3.x),您可以:

from __future__ import division
import operator, itertools

def getmin(alist):
    return min(
        (operator.div(*pair), pair)
        for pair in itertools.product(alist, repeat=2)
    )[1]

getmin([1, 2, 3, 4, 5])

EDIT: Now that I think of it and if I remember my mathematics correctly, this should also give the answer assuming that all numbers are non-negative: 编辑:现在我想到了它,如果我正确地记住了我的数学,这也应该给出答案,假设所有数字都是非负的:

def getmin(alist):
    return min(alist), max(alist)
>>> nums = [1, 2, 3, 4, 5]    
>>> min(map((lambda t: ((float(t[0])/t[1]), t)), ((x, y) for x in nums for y in nums)))[1]
(1, 5)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM