如何从列表中随机调用函数?



我是一个Python初学者,我休息了一个月,今天我回来了。在我正在阅读的学习Python的书中,作者要求我们记住真值表。我想让它更有趣,所以我想出了一个想法,试着写一个剧本,从一个列表中随机问我一些问题(我写的),我可以用"true"来回答这些问题。或";false"。问题是我在代码中使用的很多东西我还没有从书中完成,所以我使用互联网来帮助我。

这是我想到的:

print("Here are some questions for you, answer true or false.")
input("Press 'Enter' if you would like to continue.")
def a():
answer = input("1) not False: ")
print("Correct!") if answer == 'true' else print("Wrong!")
def b():
answer = input("2) not True: ")
print("Correct!") if answer == "false" else print ("Wrong!")
def c():
answer = input("3) True or False: ")
print("Correct!") if answer == "true" else print ("Wrong!")
import random
questions = [a(), b(), c()]
print(random.sample(questions, 3))

问题更多,我只用了三个来测试代码是否正常工作。到目前为止一切顺利,如果不是因为我似乎不能从列表中调用随机函数的话。

这是我的输出:输出

还有,[None, None, None]是什么意思?

我知道用我还没学过的东西不是个好主意,但我对此很兴奋。

TIA !

问题

使用父元素调用函数。您需要做的是存储对函数的引用:questions = [a, b, c].

由于None由函数隐式返回(由于缺乏显式返回;因为你只是在创建questions列表时调用了这些函数,所以你所做的就是回答每个问题(返回None),并将答案洗牌。

解决方案1

通过在questions列表中存储对函数的引用,这允许您简单地在for循环中调用遍历打乱列表的函数:

questions = [a, b, c]
for q in random.sample(questions, 3):
q()

解决方案2

你可以修改你的函数返回点,这将允许你开始跟踪你的性能:

# Import statements should always be placed at the top of the file
import random

print("Here are some questions for you, answer true or false.")
input("Press 'Enter' if you would like to continue.")  # this does nothing

def a():
answer = input("1) not False: ")
print("Correct!") if answer == "true" else print("Wrong!")
return int(answer.lower() == "true")

def b():
answer = input("2) not True: ")
print("Correct!") if answer == "false" else print ("Wrong!")
return int(answer.lower() == "false")

def c():
answer = input("3) True or False: ")
print("Correct!") if answer == "true" else print ("Wrong!")
return int(answer.lower() == "true")

questions = [a, b, c]
earned_points = [q() for q in random.sample(questions, 3)]

3

解决方案更好的方法是使用if __name__ == "__main__"模式:

import random

def a():
answer = input("1) not False: ").lower()
print("Correct!") if answer == "true" else print("Wrong!")
return int(answer == "true")

def b():
answer = input("2) not True: ").lower()
print("Correct!") if answer == "false" else print ("Wrong!")
return int(answer == "false")

def c():
answer = input("3) True or False: ").lower()
print("Correct!") if answer == "true" else print ("Wrong!")
return int(answer == "true")

if __name__ == "__main__":
print("Here are some questions for you, answer true or false.")
proceed = input("Press 'Enter' if you would like to continue.")
if proceed == '':
questions = [a, b, c]
earned_points = [q() for q in random.sample(questions, 3)]
# now do something with earned_points, for example:
# calculate and print the total points scored
# calculate and print the user's 'grade' (their score out of the total)
# calculate and print the average score
else:
print("You declined to play")

进一步提高你还可以对你的程序做许多其他的改进。

注意,在第三种解决方案中,用户的输入立即转换为小写——这简化了输入验证。你甚至可以写一个辅助函数,如果用户输入的不是'true'或'false',它就会报错。

需要注意的另一件事是,除了问题提示符和答案之外,三个函数中的代码是相同的。你可以做的一件事是实现一个通用的提问器;函数,它接受两个参数:提示符和预期的答案。然后将问题存储为2元组,如("true or false", "true")("true and false", "false")等。然后对问题元组进行洗牌,然后遍历洗牌后的列表,将它们传递给泛型问题提问者。

让我们来解码你的程序中发生了什么。

questions = [a(), b(), c()]

这个列表调用了三个函数并存储了它们的结果。如您所见,您的函数都没有返回任何东西。这使得上面创建的列表的内容都是None

但是为什么在输出中看到一个包含三个None值的列表?

那是因为print(random.sample(questions, 3))。这条线是试图让三个随机值从一个列表中,所有没有值。

现在如何问随机问题,或者在你的情况下,如何调用随机函数?

这可以通过多种方式完成。目前我能想到的一个简单的方法是:

确保将问题列表修改为:

questions = [a, b, c]

首先在问题长度范围内创建一个随机题号:

question_num = random.randint(0,len(questions)-1)

然后用问题号调用相应的问题:

questions[question_num]()

这应该每次随机问一个问题。但是如果你想继续问一个随机的问题,你可以在循环中调用上面的两行。

这个答案与你的解决方案是一致的,但是如果你想做同样的事情,有不同的有效方法。我试着把它们添加到这里。

构建一个包含两个元组的列表,每个元组包含问题和正确答案。然后你的程序变得非常简洁:

import random
questions = [('not False', 'true'),
('not True', 'false'),
('True or False', 'true')
]
for i, (q, a) in enumerate(random.sample(questions, k=len(questions)), 1):
answer = input(f'{i}) {q}: ')
print("Correct!" if answer == a else "Wrong!")

最新更新