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

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/

10-16 15:42
查看更多