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

时间:2021-06-30 14:30:02

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, jused to calculate this minimum value.

对于列表中的每个元素i映射列表中的所有元素的一些函数,将i和j作为参数将结果存储在主列表中,在主列表中找到最小值,并返回参数i,jused以计算此值最低价值。

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.

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

7 个解决方案

#1


42  

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

你可以使用list comprehensions和min()(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,或者从__future__ import division执行,以便1/5正确等于0.2而不是0。

#2


10  

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)

#3


3  

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.

如果有什么不清楚,请告诉我。

#4


3  

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]

#5


2  

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.

当然,除非你在那里有负面影响。在这种情况下,这将不起作用,因为你实际上想要最小和最大绝对值 - 分子应该接近于零,并且分母在任何方向上都远离它。而双重否定将打破它。

#6


1  

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)

#7


0  

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

#1


42  

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

你可以使用list comprehensions和min()(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,或者从__future__ import division执行,以便1/5正确等于0.2而不是0。

#2


10  

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)

#3


3  

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.

如果有什么不清楚,请告诉我。

#4


3  

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]

#5


2  

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.

当然,除非你在那里有负面影响。在这种情况下,这将不起作用,因为你实际上想要最小和最大绝对值 - 分子应该接近于零,并且分母在任何方向上都远离它。而双重否定将打破它。

#6


1  

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)

#7


0  

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