简体   繁体   English

随机调用函数执行

[英]Randomly calling functions to execute

I have made this short questionnaire: 我做了这个简短的调查表:

from random import randint

def pancakes():
    q = raw_input("Do you like pancakes?")
    if q == "yes":
        print("Great!")
    elif q == "no":
        print("Hmmm...")

def french_toast():
    q = raw_input("Do you like french toast?")
    if q == "yes":
        print("Oh!")
    elif q == "no":
        print("Same here!")

def random():
    num = 2
    while num > 0:
        random = randint(1, 2)
        if random == 1:
            num = num -1
            pancakes()
         elif random == 2:
             num = num -1
             french_toast()

random()

My goal here was to get the questions in a random order. 我的目标是随机获得问题。 But sometimes the same question will be asked twice since it's randomly chosen. 但有时,由于是随机选择的,因此同一问题会被询问两次。

So how can I make it ask the same question only once? 那么,如何使它只问一次相同的问题呢?

Instead of a while loop, I'd suggest you use a for loop in conjunction with random.sample . 建议不要使用while循环,而是将for循环与random.sample结合使用。 Create a list of functions before-hand to provide to sample : 预先创建要提供给sample的函数列表:

from random import sample

funcs = [french_toast, pancakes]
for func in sample(funcs, len(funcs)):
    func()

this will now loop through all functions randomly selecting a function in each iteration. 现在,它将遍历所有函数,并在每次迭代中随机选择一个函数。

Alternatively, you could shuffle the list (performs in-place) with random.shuffle and then iterate through it, that will be faster too (though, speed shouldn't be the biggest concern here): 或者,您可以使用random.shuffleshuffle random.shuffle列表(执行原位),然后对其进行遍历,这也会更快(不过,速度并不是此处的最大问题):

from random import shuffle

funcs = [french_toast, pancakes]
shuffle(funcs)
for func in funcs:
    func()

Put these in a function if so required: 如果需要,将它们放在一个函数中:

from random import shuffle

# use *funcs for passing arbitrary number of 
# functions as positional arguments.
def call_funcs_randomly(funcs):
    shuffle(funcs)
    for func in funcs:
        func()

and call them: 并给他们打电话:

call_funcs_randomly([french_toast, pancakes])

As a comment noted, don't use random as a function name, it has the possibility of masking the module random leading to odd looking errors. 如注释中所述,不要将random用作函数名称,它可能会掩盖模块的random从而导致出现奇怪的错误。

I would use random.sample Link . 我会使用random.sample Link Just create a list of indices to your questions and sample 2 of them. 只需为您的问题创建一个索引列表,然后对其中的2个进行抽样。

EDIT: 编辑:

additionally, you could use random.shuffle Link : 另外,您可以使用random.shuffle Link

random.shuffle(questions)
for question in questions:
    # process your random question once 

how about this for your last question ( random is not a good name! you might overwrite the module of the same name [although you are fine the way do do it right now]) 最后一个问题的random如何( random不是一个好名字!您可能会覆盖同名的模块[尽管您可以按目前的方式进行操作])

def random_questions():
    eligible_questions = [pancakes, french_toast]
    while eligible_questions:
        question = random.choice(eligible_questions)
        eligible_questions.remove(question)
        question()

put the questions in a list, select one with random.choice , remove it from the list and execute it. 将问题放在列表中,使用random.choice选择一个,从列表random.choice删除并执行。 stop if the question list is empty. 如果问题列表为空,则停止。 this way every question is selected exactly once. 这样,每个问题都会被选择一次。

this is easily extended if you want to add more questions. 如果您想添加更多问题,可以轻松扩展。

on second thought: the shuffle version in Jim Fasarakis-Hilliard's answer is a lot cleaner! 关于第二个想法:在shuffle版本吉姆Fasarakis -希利亚德的回答是很多清洁剂!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM