python - 从列表中调用函数 - Python

标签 python function call

我有一个字符串列表,我想为字符串中的每个字符调用一个函数。当我为每个函数分配变量时,我不想让它们运行,我只想在遍历字符串时调用它们。这是我的代码:

import random

def make_s():
    result = ''

    V = make_v
    C = make_c
    P = make_p
    B = make_b

    structs = ['VPCVBCC', 'VCVVC', 'VVPCC', 'VCVBCC', 'VPCCVBC', 'VCVCC', 'VPCBC', \
            'VVPCVBCC', 'VCVC', 'VPCVVBC']

    struct = random.choice(structs)

    for elem in struct:
        /* Call function defined above and add the result to the result string */
        result += elem()

    return result

执行此操作的最佳方法是什么?

非常感谢:)

最佳答案

你很接近。您应该只将字符映射到函数,而不是分配给特定变量。

import random

def make_s():
    result = ''

    # Here we have a mapping between the characters you see,
    # and the functions you want to call.
    my_funcs = {"V": make_v,
                "C": make_c,
                "P": make_p,
                "B": make_b}

    structs = ['VPCVBCC', 'VCVVC', 'VVPCC', 'VCVBCC', 'VPCCVBC', 'VCVCC', 'VPCBC', \
            'VVPCVBCC', 'VCVC', 'VPCVVBC']

    struct = random.choice(structs)

    for elem in struct:
        # Lookup the function in your dictionary
        func_to_call = my_funcs[elem]
        # And call it!
        result += func_to_call()

    return result

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

相关文章:

python - 在 python 中跟踪图像

python - 将列表元素作为单独的字符串传递给 Django 方法

在 C 中调用以字符串变量命名的函数

c++ - 为什么 gprof 告诉我从 main() 只调用一次的函数被调用了 102 次?

python - pymysql callproc() 似乎影响后续选择

python - Python 装饰器的参数

c - 为什么回调函数的名字叫callback?

java - 返回值的三元运算符 - Java/Android

Java异步方法调用

r - 有条件地修改父函数的行为