【问题标题】:How to initilise a list that contains custom functions without python running those functions during initialisation?如何初始化包含自定义函数的列表,而无需 python 在初始化期间运行这些函数?
【发布时间】:2020-05-24 16:31:56
【问题描述】:

短版:

  • 如何将函数存储在列表中,并且仅在使用列表中的索引位置调用它们时才执行它们?

加长版:

所以我正在编写一个程序,它可以掷出用户选择数量的六面骰子,将结果存储在列表中,然后将结果/数据组织到字典中。

收集数据后,程序为用户提供从 0 到 2 的选项以供选择,并要求用户键入与他们想要的选项相对应的数字。

在用户输入之后,一个变量,比如说 TT,被分配给它。我希望程序使用 TT 来识别要运行的函数,该函数包含在名为“Executable_options”的列表中,方法是使用 TT 作为该函数在列表中的索引位置。

我遇到的问题是,在定义函数之后,我必须在一行上包含包含函数的列表,并且当我初始化列表时,它会遍历并在我不这样做时按顺序执行其中的所有函数'不想。我只是希望他们在以后打电话的名单中。

我尝试在没有任何函数的情况下初始化列表,然后单独附加函数,但每次将函数附加到列表时,它也会被执行。

def results():
def Rolling_thunder():
def roll_again():

函数包含东西,但对于手头的问题不必显示

Executable_options = []
Executable_options.append(results())
Executable_options.append(Rolling_thunder())
Executable_options.append(roll_again)

options = len(Executable_options)

我对 Python 还比较陌生,所以我仍然对它有所了解。我已尝试在现有帖子中搜索此问题的答案,但找不到任何内容,因此我认为我只是在搜索中使用了错误的关键词。

非常感谢您花时间阅读本文并提供答案。

编辑:代码现在可以工作了

【问题讨论】:

    标签: python-3.x list initialization custom-function


    【解决方案1】:

    函数名末尾的() 调用它 - 即results() 是对results 方法的调用。

    在没有调用的情况下简单地追加到列表中 - 即:

    Executable_options.append(results)

    然后您可以通过以下方式调用它:例如:

    Executable_options[0]()

    【讨论】:

    • 您好,感谢您的回复。现在更有意义了!
    【解决方案2】:

    根据您给定的数据,代码将如下所示:

    def results():
    def Rolling_thunder():
    def roll_again():
    
    Executable_options = []
    Executable_options.append(results)
    Executable_options.append(Rolling_thunder)
    Executable_options.append(roll_again)
    
    for i in range(0,len(Executable_options)):
        Executable_options[i]()
    

    这对你有用。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-10-02
      • 1970-01-01
      • 1970-01-01
      • 2012-08-25
      • 1970-01-01
      • 2017-09-20
      相关资源
      最近更新 更多