Skip to main content
 首页 » 编程设计

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

2025年05月04日16txw1958

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

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