【问题标题】:How to use random.choice() with functions? [duplicate]如何将 random.choice() 与函数一起使用? [复制]
【发布时间】:2019-10-10 14:58:04
【问题描述】:

我在一个文件中列出了 18 个作为函数的多项选择题,我想从一个主文件中随机调用其中的 10 个问题。如果我将 random.choice() 与整数或字符串列表一起使用,它可以正常工作,但是如果我将函数列表传递给它,它会按顺序运行所有函数,而忽略我设置的范围。我在论坛上阅读了很多文档、帮助文件和类似案例,但我仍然摸不着头脑。在这一点上,我认为 random.choice 不会做我需要的事情。有人看到我的错误或知道替代方案吗?

我尝试过 random.choice()、.choices()、.shuffle() 我尝试在列表和字典中传递函数,将列表名称或整个选项列表直接输入到 .choice()、printing(random.choice(list)) 中,但每次都得到相同的结果。

import random

def Q1():
    print('Question 1')
def Q2():
    print('Question 2')
def Q3():
    print('Question 3')    

list = [Q1(),Q2(),Q3()]
for i in range(5):
    random.choice(list)
    i+=i

【问题讨论】:

    标签: python function random


    【解决方案1】:

    您可能的意思是,您只需稍微调整一下您的代码:

    import random
    
    def Q1():
        print('Question 1')
    def Q2():
        print('Question 2')
    def Q3():
        print('Question 3')    
    
    list = [Q1, Q2, Q3]
    for i in range(5):
        random.choice(list)()
    

    【讨论】:

      【解决方案2】:

      random.choice() 有效,你只需要更正你的语法:

      import random
      
      def Q1():
          print('Question 1')
      def Q2():
          print('Question 2')
      def Q3():
          print('Question 3')    
      
      list = [Q1, Q2, Q3]
      for i in range(5):
          random.choice(list)()
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-05-10
        • 1970-01-01
        • 2021-10-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-09-16
        相关资源
        最近更新 更多