列表中的 Python 函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15209552/
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 functions within lists
提问by Hovestar
So today in computer science I asked about using a function as a variable. For example, I can create a function, such as returnMe(i)and make an array that will be used to call it. Like h = [help,returnMe]and then I can say h1 and it would call returnMe("Bob"). Sorry I was a little excited about this. My question is is there a way of calling like h.append(def function)and define a function that only exists in the array?
所以今天在计算机科学中,我询问了使用函数作为变量的问题。例如,我可以创建一个函数,例如returnMe(i)并制作一个用于调用它的数组。就像h = [help,returnMe]然后我可以说 h1 它会调用returnMe("Bob"). 抱歉,我对此有点兴奋。我的问题是有没有办法调用 likeh.append(def function)并定义一个只存在于数组中的函数?
EDIT:
编辑:
Here Is some code that I wrote with this! So I just finished an awesome FizzBuzz with this solution thank you so much again! Here's that code as an example:
这是我用这个写的一些代码!所以我刚刚用这个解决方案完成了一个很棒的 FizzBuzz 再次非常感谢你!以该代码为例:
funct = []
s = ""
def newFunct(str, num):
return (lambda x: str if(x%num==0) else "")
funct.append(newFunct("Fizz",3))
funct.append(newFunct("Buzz",5))
for x in range(1,101):
for oper in funct:
s += oper(x)
s += ":"+str(x)+"\n"
print s
采纳答案by mgilson
You can create anonymous functions using the lambdakeyword.
您可以使用lambda关键字创建匿名函数。
def func(x,keyword='bar'):
return (x,keyword)
is roughly equivalent to:
大致相当于:
func = lambda x,keyword='bar':(x,keyword)
So, if you want to create a list with functions in it:
所以,如果你想创建一个包含函数的列表:
my_list = [lambda x:x**2,lambda x:x**3]
print my_list[0](2) #4
print my_list[1](2) #8
回答by Daniel Roseman
Not really in Python. As mgilson shows, you can do this with trivial functions, but they can only contain expressions, not statements, so are very limited (you can't assign to a variable, for example).
不是真的在 Python 中。正如 mgilson 所示,您可以使用简单的函数来做到这一点,但它们只能包含表达式,不能包含语句,因此非常有限(例如,您不能分配给变量)。
This is of course supported in other languages: in Javascript, for example, creating substantial anonymous functions and passing them around is a very idiomatic thing to do.
这当然在其他语言中得到支持:例如,在 Javascript 中,创建大量匿名函数并将它们传递出去是一件非常惯用的事情。
回答by Hyperboreus
You can create the functions in the original scope, assign them to the array and then delete them from their original scope. Thus, you can indeed call them from the array but not as a local variable. I am not sure if this meets your requirements.
您可以在原始作用域中创建函数,将它们分配给数组,然后将它们从原始作用域中删除。因此,您确实可以从数组中调用它们,但不能作为局部变量。我不确定这是否符合您的要求。
#! /usr/bin/python3.2
def a (x): print (x * 2)
def b (x): print (x ** 2)
l = [a, b]
del a
del b
l [0] (3) #works
l [1] (3) #works
a (3) #fails epicly
回答by Raufio
You can create a list of lambdafunctions to increment by every number from 0 to 9 like so:
您可以创建一个lambda函数列表,以从 0 到 9 的每个数字递增,如下所示:
increment = [(lambda arg: (lambda x: arg + x))(i) for i in range(10)]
increment[0](1) #returns 1
increment[9](10) #returns 19
Side Note:
边注:
I think it's also important to note that this (function pointers not lambdas) is somewhat like how python holds methods in most classes, except instead of a list, it's a dictionary with function names pointing to the functions. In many but not all cases instance.func(args)is equivalent to instance.__dict__['func'](args)or type(class).__dict__['func'](args)
我认为同样重要的是要注意这个(函数指针而不是 lambdas)有点像 python 在大多数类中保存方法的方式,除了它不是一个列表,它是一个函数名称指向函数的字典。在许多但并非所有情况下instance.func(args),等价于instance.__dict__['func'](args)或type(class).__dict__['func'](args)

