从列表中调用函数 - Python

时间:2016-12-07 17:14:32

标签: 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

这样做的最佳方法是什么?

非常感谢:)

2 个答案:

答案 0 :(得分:4)

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

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

答案 1 :(得分:2)

使用字典将字符映射到函数调用的类似方法,使用列表理解和更简洁一点。字符串join函数:

import random
def make_s():
    fDict = {'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)
    return ''.join([fDict[elem] for elem in struct])