函数字典返回每个函数

2024-09-30 20:19:17 发布

您现在位置:Python中文网/ 问答频道 /正文

我很难从预定义函数的字典中返回特定函数。这是我的密码:

import random

def bos1():
    print ("function 1")

def bos2():
    print ("function 2")

def bos3():
    print("function 3")

def bos4():
    print("function 4")
count = 0

while True :
    if count <4:

        bos = "bos"
        poz = random.randint(3, 4)
        bos = bos+str(poz)


        bosdict = {'bos1': bos1(),'bos2':bos2(),'bos3':bos3(),'bos4':bos4()}
        count += 1
        print("please only printe one",bosdict[bos])
        print("count:\n", count)

        input("")

    else:

        bos = "bos"
        poz = random.randint(1, 2)
        bos = bos+str(poz)


        bosdict = {'bos1': bos1(),'bos2':bos2(),'bos3':bos3(),'bos4':bos4()}
        count += 1
        print("please only printe one",bosdict['bos'])
        print("count:\n", count)

        input("")

我已经创建了一个使用算术函数的程序的成功版本。它将返回与每次迭代时连接的字符串相关的适当函数。但是,对于要返回字符串的函数,它会在每次迭代时返回字典中的所有四个函数。为什么会发生这种情况?我如何才能使它的行为与算术字典相同?你知道吗


Tags: 函数字典defcountfunctionrandomprintrandint
1条回答
网友
1楼 · 发布于 2024-09-30 20:19:17

你不是在创建一个函数字典,而是一个函数调用的字典(因为你的函数什么都不返回),所有函数都在创建字典时执行。你知道吗

删除dict中的(),在检索dict中的值后使用它来调用函数:

bosdict = {'bos1': bos1,'bos2':bos2,'bos3':bos3,'bos4':bos4}

像这样调用随机函数:

bosdict[random.choice(list(bosdict.keys()))]()

或者更简单,在这种情况下,您不需要键,只需要值:

random.choice(list(bosdict.values()))()

或者使用随机索引生成的名称:

bosdict["bos{}".format(count)]()

注意,动态调用函数只有在函数计算速度慢或有副作用或参数时才有意义,否则最好创建一个静态字典(使用return而不是Chris提到的print)。你知道吗

相关问题 更多 >