Python -赋值列表



有没有办法让

statements = [statement1, statement2, statement3, ...]
在Python中

?

我希望能够做到:

run statements[i]

或:

f = statements[j](其中f为函数)

注:我想有一个赋值语句的列表(lambda不会工作),我宁愿不创建函数。例如:

switch = [output = input, output = 2 * input, output = input ** 2]

除了为每个条目定义一个函数之外,还有其他方法吗?

谢谢大家回答我的问题。

是。函数在python中是第一类公民:也就是说,你可以将它们作为参数传递,甚至将它们存储在数组中。

有一个函数列表并不罕见:你可以像这样用python构建一个简单的注册表:

#!/usr/bin/env python
processing_pipeline = []
def step(function):
    processing_pipeline.append(function);
    return function
@step
def step_1(data):
    print("processing step1")
@step
def step_2(data):
    print("processing step2")
@step
def step_3(data):
    print("processing step3")
def main():
    data = {}
    for process in processing_pipeline:
        process(data)
if __name__ == '__main__':
    main()

这里的processing_pipeline只是一个函数列表。step是一个所谓的装饰器-函数,其工作方式类似于闭包。python解释器在解析文件时将每个修饰的@step添加到管道中。

您可以使用迭代器或通过processing_pipeline[i]访问该函数:尝试添加processing_pipeline[2](data)

我想能够做到:run statements[i]

你可以通过exec:

statements = ["result=max(1,2)","print(result)"]
for idx in range(len(statements)):
    exec(statements[idx])
print(result)

希望有帮助!

这很好:

def addbla(item):
    return item + ' bla'
items = ['Trump', 'Donald', 'tax declaration']
new_items = [addbla(item) for item in items]
print(new_items)

它在items的每个条目中添加了政治声明:)

如果要运行语句块,请使用函数。

def run_statements():
    func()
    for i in range(3):
        if i > 1:
            break
    extra_func()
run_statements()

如果要从列表中选择特定的语句,请将每个语句包装在一个函数中:

def looper():
    for i in range(3):
        if i>1:
            break
def func():
    print('hello')
statements = [looper, func]
statements[-1]()

如果你的语句是简单的函数调用,你可以把它们直接放到一个列表中,而不需要创建包装器函数。

你可以这样做:

funcs = [min, max, sum]
f = funcs[0]
funcs[1](1,2,3) # out 3
funcs[2]([1,2,3]) # out 6

既然我们已经有了其他的方法,我想我应该把这个扔掉:

def a(input):
    return pow(input, 3)
def b(input):
    return abs(input)
def c(input):
    return "I have {0} chickens".format(str(input))
#make an array of functions
foo = [a,b,c]
#make a list comprehension of the list of functions
dop = [x(3) for x in foo]
print dop

最新更新