【问题标题】:Python. Is there a way to pick a random def?Python。有没有办法选择一个随机的def?
【发布时间】:2018-12-04 11:58:31
【问题描述】:

我想将每个 Callout 存储在 def 函数中 例如:

def shooting():
    print("bang bang")

def mugging():
    print("money, now!")
callout = ['shooting', 'mugging']
randomthing = random.choice(callout)
print(randomthing + "()")

所以每个标注都存储在 def 函数中。然后在标注和随机事物中随机化。然后(我知道这部分是错误的)我希望它调用 mugging() 或 shooing() 但有 50/50 的机会。

【问题讨论】:

  • @jhpratt 你不需要“lambdas”。 lambda只是定义了一个函数,和def一样;不管它们是如何定义的,你都可以拥有一个函数数组。
  • 只需将您的代码更改为callout = [shooting, mugging],存储实际函数而不是它们的名称。然后,您只需执行 randomthing() 即可调用您选择的任何函数。

标签: python function random


【解决方案1】:

你几乎拥有它!只需删除引号,并直接存储函数名称。 Python 中的函数就像变量一样:

callout = [shooting, mugging]
randomthing = random.choice(callout)
print(randomthing())

【讨论】:

  • 这似乎效果最好!但现在它似乎在 bang bang 下添加了 None 这个词。示例:砰砰无
  • @T.ps 那是因为您的每个函数都执行print,然后不返回任何内容。如果您不返回任何内容,则默认值为None。所以当你print(randomthing()) 时,它会打印出None。您可能想要做的是将您的函数更改为 return 一个字符串,而不是 printing 它。
  • 我该如何解决这个问题?
  • 您可以将函数更改为return 'bang bang'return 'money, now!' 或者,您可以调用randomthing(),而不是print(randomthing())
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-03-11
  • 1970-01-01
  • 1970-01-01
  • 2015-12-18
  • 1970-01-01
  • 2011-02-01
  • 2017-05-29
相关资源
最近更新 更多