Python,lambda,求最小值

发布于 2024-08-08 22:57:28 字数 957 浏览 4 评论 0原文

我有 foreach 函数,它在它包含的每个元素上调用指定的函数。我想从这些元素中获得最少的值,但我不知道如何编写 lambda 或函数,甚至不知道如何编写一个可以管理它的类。 感谢您的每一个帮助。


I use my foreach function like this:

o.foreach( lambda i: i.call() )

或者

o.foreach( I.call )

我不喜欢制作列表或其他对象。我想迭代它并找到最小值。

我设法编写一个类来进行思考,但应该有一些比这更好的解决方案:

class Min:                                           
    def __init__(self,i):                        
        self.i = i                              
    def get_min(self):                               
        return self.i                                
    def set_val(self,o):                             
        if o.val < self.i: self.i = o.val

m = Min( xmin )
self.foreach( m.set_val )                            
xmin = m.get_min()

好的,所以我认为我的 .foreach 方法是非 python 的想法。我应该让我的类可迭代,因为所有解决方案都基于列表,然后一切都会变得更容易。

在C#中,这样的lambda函数不会有问题,所以我认为python也有那么强大。

I have foreach function which calls specified function on every element which it contains. I want to get minimum from thise elements but I have no idea how to write lambda or function or even a class that would manage that.
Thanks for every help.


I use my foreach function like this:

o.foreach( lambda i: i.call() )

or

o.foreach( I.call )

I don't like to make a lists or other objects. I want to iterate trough it and find min.

I manage to write a class that do the think but there should be some better solution than that:

class Min:                                           
    def __init__(self,i):                        
        self.i = i                              
    def get_min(self):                               
        return self.i                                
    def set_val(self,o):                             
        if o.val < self.i: self.i = o.val

m = Min( xmin )
self.foreach( m.set_val )                            
xmin = m.get_min()

Ok, so I suppose that my .foreach method is non-python idea. I should do my Class iterable because all your solutions are based on lists and then everything will become easier.

In C# there would be no problem with lambda function like that, so I though that python is also that powerful.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

命比纸薄 2024-08-15 22:57:28

Python 内置支持查找最小值

>>> min([1, 2, 3])
1

如果您需要处理列表首先使用函数,您可以使用 map 来做到这一点:

>>> def double(x):
...    return x * 2
... 
>>> min(map(double, [1, 2, 3]))
2

或者您可以花哨与 列表推导式生成器表达式,例如:

>>> min(double(x) for x in [1, 2, 3])
2

Python has built-in support for finding minimums:

>>> min([1, 2, 3])
1

If you need to process the list with a function first, you can do that with map:

>>> def double(x):
...    return x * 2
... 
>>> min(map(double, [1, 2, 3]))
2

Or you can get fancy with list comprehensions and generator expressions, for example:

>>> min(double(x) for x in [1, 2, 3])
2
空心空情空意 2024-08-15 22:57:28

您无法使用 foreach 和 lambda 来做到这一点。如果您想以函数式风格执行此操作而不实际使用 min,您会发现 reduce 与您尝试定义的函数非常接近。

l = [5,2,6,7,9,8]
reduce(lambda a,b: a if a < b else b, l[1:], l[0])

You can't do this with foreach and a lambda. If you want to do this in a functional style without actually using min, you'll find reduce is pretty close to the function you were trying to define.

l = [5,2,6,7,9,8]
reduce(lambda a,b: a if a < b else b, l[1:], l[0])
在梵高的星空下 2024-08-15 22:57:28

编写 foreach 方法不是很 Pythonic。您最好将其设为迭代器,以便它可以与 min 等标准 Python 函数一起使用。

不要这样写:

def foreach(self, f):
    for d in self._data:
        f(d)

这样写:

def __iter__(self):
    for d in self._data:
        yield d

现在您可以将 min 调用为 min(myobj)

Writing foreach method is not very pythonic. You should better make it an iterator so that it works with standard python functions like min.

Instead of writing something like this:

def foreach(self, f):
    for d in self._data:
        f(d)

write this:

def __iter__(self):
    for d in self._data:
        yield d

Now you can call min as min(myobj).

风月客 2024-08-15 22:57:28

我有 foreach 函数,它在它包含的每个元素上调用指定的函数

。从您随后发布的评论来看,您已经重新发明了内置的 map 函数。

听起来您正在寻找类似的内容:

min(map(f, seq))

其中 f 是您想要对列表中的每个项目调用的函数。

正如 gnibbler 所示,如果您想在 f(x) 返回最小值的序列中查找值 x,您可以使用:

min(seq, key=f)

...除非您想要查找 seqf 返回最小值的所有项。例如,如果 seq 是字典列表,

min(seq, key=len)

则将返回列表中项目数最少的第一个字典,而不是包含该项目数的所有字典。

要获取函数 f 返回最小值的序列中所有项目的列表,请执行以下操作:

values = map(f, seq)
result = [seq[i] for (i, v) in enumerate(values) if v == min(values)]

I have foreach function which calls specified function on every element which it contains

It sounds, from the comment you subsequently posted, that you have re-invented the built-in map function.

It sounds like you're looking for something like this:

min(map(f, seq))

where f is the function that you want to call on every item in the list.

As gnibbler shows, if you want to find the value x in the sequence for which f(x) returns the lowest value, you can use:

min(seq, key=f)

...unless you want to find all of the items in seq for which f returns the lowest value. For instance, if seq is a list of dictionaries,

min(seq, key=len)

will return the first dictionary in the list with the smallest number of items, not all dictionaries that contain that number of items.

To get a list of all items in a sequence for which the function f returns the smallest value, do this:

values = map(f, seq)
result = [seq[i] for (i, v) in enumerate(values) if v == min(values)]
好多鱼好多余 2024-08-15 22:57:28

好的,您需要了解一件事:lambda 为您创建一个函数对象。但普通的 def 也是如此。看这个例子:

lst = range(10)

print filter(lambda x: x % 2 == 0, lst)

def is_even(x):
    return x % 2 == 0

print filter(is_even, lst)

这两个都有效。它们产生相同的结果。 lambda 创建一个未命名的函数对象; def 创建一个命名函数对象。 filter() 不关心函数对象是否有名称。

因此,如果 lambda 的唯一问题是无法在 lambda 中使用 =,那么您可以使用 创建一个函数>定义。

现在,也就是说,我不建议您使用 .foreach() 方法来查找最小值。相反,让您的主对象返回一个值列表,然后简单地调用 Python min() 函数。

lst = range(10)
print min(lst)

编辑:我同意接受的答案更好。与其返回值列表,不如定义 __iter__() 并使对象可迭代。

Okay, one thing you need to understand: lambda creates a function object for you. But so does plain, ordinary def. Look at this example:

lst = range(10)

print filter(lambda x: x % 2 == 0, lst)

def is_even(x):
    return x % 2 == 0

print filter(is_even, lst)

Both of these work. They produce the same identical result. lambda makes an un-named function object; def makes a named function object. filter() doesn't care whether the function object has a name or not.

So, if your only problem with lambda is that you can't use = in a lambda, you can just make a function using def.

Now, that said, I don't suggest you use your .foreach() method to find a minimum value. Instead, make your main object return a list of values, and simply call the Python min() function.

lst = range(10)
print min(lst)

EDIT: I agree that the answer that was accepted is better. Rather than returning a list of values, it is better to define __iter__() and make the object iterable.

清风挽心 2024-08-15 22:57:28

假设你有

>>> seq = range(-4,4)
>>> def f(x):
...  return x*x-2

f 的最小值

>>> min(f(x) for x in seq)
-2

和 x 的最小值,

>>> min(seq, key=f)
0

当然你也可以使用 lambda,

>>> min((lambda x:x*x-2)(x) for x in range(-4,4))
-2

但这有点难看,这里的 map 看起来更好

>>> min(map(lambda x:x*x-2, seq))
-2

>>> min(seq,key=lambda x:x*x-2)
0

Suppose you have

>>> seq = range(-4,4)
>>> def f(x):
...  return x*x-2

for the minimum value of f

>>> min(f(x) for x in seq)
-2

for the value of x at the minimum

>>> min(seq, key=f)
0

of course you can use lambda too

>>> min((lambda x:x*x-2)(x) for x in range(-4,4))
-2

but that is a little ugly, map looks better here

>>> min(map(lambda x:x*x-2, seq))
-2

>>> min(seq,key=lambda x:x*x-2)
0
不如归去 2024-08-15 22:57:28

你可以使用这个:

x = lambda x,y,z: min(x,y,z)
print(x(3,2,1))

You can use this:

x = lambda x,y,z: min(x,y,z)
print(x(3,2,1))
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文