python - 使用列表推导调用函数列表

标签 python list function list-comprehension

我可以调用函数列表并使用列表推导吗?

def func1():return 1
def func2():return 2
def func3():return 3

fl = [func1,func2,func3]

fl[0]()
fl[1]()
fl[2]()

我知道我能做到

for f in fl:
   f()

但我可以在下面做吗?

[f() for f in fl]

如果我的函数列表在类里面,那么对于那些好心人的另一个问题,例如

class F:

    def __init__(self):
        self.a, self.b, self.c = 0,0,0

    def func1(self):
        self.a += 1

    def func2(self):
        self.b += 1

    def func3(self):
        self.c += 1

    fl = [func1,func2,func3]

fobj= F()

for f in fobj.fl:
    f()

有用吗?

最佳答案

>>> [f() for f in fl]
[1, 2, 3]

绝对:)

关于python - 使用列表推导调用函数列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5461571/

相关文章:

python - 如何在 Tensorflow 中对无维度的张量进行切片

python - 将条目添加到字典列表中

C 随机,有问题

python - 包含列表的递归列表

c - 函数引用返回的变量给出了奇怪的值

iphone - iPhone 上 SQLite 的用户定义函数

python - 在代码中升级 python 模块

python - 如何使用seaborn和ipywidgets制作交互式条形图

python - 尝试使用 itertools.permutations 时出现 MemoryError,如何使用更少的内存?

python - 将列表转换为字典