简体   繁体   中英

Python functions within lists

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?

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:

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

You can create anonymous functions using the lambda keyword.

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

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

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.

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

You can create a list of lambda functions to increment by every number from 0 to 9 like so:

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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