Python,lambda,找到最小值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1634054/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Python, lambda, find minimum
提问by qba
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.
我有 foreach 函数,它在它包含的每个元素上调用指定的函数。我想从 thise 元素中获得最小值,但我不知道如何编写 lambda 或函数,甚至不知道如何编写一个可以管理它的类。感谢您的每一个帮助。
我像这样使用我的 foreach 函数:
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.
好的,所以我想我的 .foreach 方法是非 Python 的想法。我应该做我的 Class iterable 因为你所有的解决方案都基于列表,然后一切都会变得更容易。
In C# there would be no problem with lambda function like that, so I though that python is also that powerful.
在 C# 中,像这样的 lambda 函数没有问题,所以我认为 python 也很强大。
采纳答案by Anand Chitipothu
Writing foreach
method is not very pythonic. You should better make it an iterator so that it works with standard python functions like min
.
编写foreach
方法不是很pythonic。您最好将其设为迭代器,以便它可以与标准的 Python 函数(如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)
.
现在您可以调用min
as min(myobj)
。
回答by Ryan Bright
Python has built-in support for finding minimums:
Python 内置支持查找最小值:
>>> min([1, 2, 3])
1
If you need to process the list with a function first, you can do that with map:
如果你需要先用函数处理列表,你可以用map来做:
>>> def double(x):
... return x * 2
...
>>> min(map(double, [1, 2, 3]))
2
Or you can get fancy with list comprehensionsand generator expressions, for example:
>>> min(double(x) for x in [1, 2, 3])
2
回答by Chuck
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.
你不能用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])
回答by Robert Rossney
I have foreach function which calls specified function on every element which it contains
我有 foreach 函数,它在它包含的每个元素上调用指定的函数
It sounds, from the comment you subsequently posted, that you have re-invented the built-in map
function.
从您随后发表的评论来看,您似乎重新发明了内置map
函数。
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.
f
您要对列表中的每个项目调用的函数在哪里。
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:
正如 gnibbler 所示,如果您想x
在序列中找到f(x)
返回最低值的值,您可以使用:
min(seq, key=f)
...unless you want to find allof the items in seq
for which f
returns the lowest value. For instance, if seq
is a list of dictionaries,
...除非你想找到所有的项目中seq
为其f
返回的最低值。例如,如果seq
是字典列表,
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:
要获取函数f
返回最小值的序列中所有项目的列表,请执行以下操作:
values = map(f, seq)
result = [seq[i] for (i, v) in enumerate(values) if v == min(values)]
回答by steveha
Okay, one thing you need to understand: lambda
creates a function object for you. But so does plain, ordinary def
. Look at this example:
好的,您需要了解一件事: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)
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.
这两个都有效。它们产生相同的结果。 lambda
制作一个未命名的函数对象;def
创建一个命名的函数对象。 filter()
不关心函数对象是否有名称。
So, if your only problem with lambda
is that you can't use =
in a lambda
, you can just make a function using def
.
所以,如果你唯一的问题lambda
是你不能=
在 a 中使用lambda
,你可以使用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.
现在,也就是说,我不建议您使用您的.foreach()
方法来找到最小值。相反,让您的主对象返回一个值列表,然后简单地调用 Pythonmin()
函数。
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.
编辑:我同意接受的答案更好。与其返回值列表,不如定义__iter__()
对象并使对象可迭代。
回答by John La Rooy
Suppose you have
假设你有
>>> seq = range(-4,4)
>>> def f(x):
... return x*x-2
for the minimum value of f
对于 f 的最小值
>>> min(f(x) for x in seq)
-2
for the value of x at the minimum
对于 x 的最小值
>>> min(seq, key=f)
0
of course you can use lambda too
当然你也可以使用 lambda
>>> 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