想要使用两个数组或列表创建一个问答游戏,但是不知道如何将一个列表中的元素与另一个列表中的元素相关联。
2、解决方案
使用 Python 中的字典
问题代码
import random
mylist = ['A','B','C']
answer = ['1','2','3']
value = random.choice(mylist)
print (value)
input()
mylist.remove(value)
value = random.choice(mylist)
mylist.remove(value)
print (value)
input()
value = random.choice(mylist)
print(value)
mylist.remove(value)
问题描述
以下代码尝试创建一个简单的问答游戏,但无法将问题与其对应的答案相关联。其具体问题如下:
- 无法将问题列表
mylist中的元素与答案列表answer中的元素相关联。 - 无法让用户在看到问题后输入答案并判断其是否正确。
- 无法跟踪用户答对的题目数量。
- 无法设置游戏轮数和每轮题目的数量。
使用 Python 中的类
解决方案代码
import sys
import random
class Question(object):
def __init__(self, question, answer, options):
self.question = question
self.answer = answer
self.options = options
def ask(self):
print(self.question + "?")
for n, option in enumerate(self.options):
print("%d) %s" % (n + 1, option))
response = int(sys.stdin.readline().strip()) # answers are integers
if response == self.answer:
print("CORRECT")
else:
print("wrong")
questions = [
Question("How many legs on a horse", 4, ["one", "two", "three", "four", "five"]),
Question("How many wheels on a bicycle", 2, ["one", "two", "three", "twenty-six"]),
# more verbose formatting
Question(question="What colour is a swan in Australia",
answer=1,
options=["black", "white", "pink"]), # the last one can have a comma, too
]
random.shuffle(questions) # randomizes the order of the questions
for question in questions:
question.ask()
解决方案描述
- 使用
Question类来表示一个问题,每个问题有三个属性:question(问题)、answer(答案)和options(选项)。 - 使用
random模块打乱问题的顺序,使每次游戏的问题顺序不同。 - 使用一个
for循环来遍历问题列表,并调用每个问题的ask方法来显示问题并获取用户的答案。 - 根据用户的答案,判断是否正确并输出相应的提示。
使用 Python 中的字典
解决方案代码
import sys
questions = [
{
'question': 'How many legs on a horse',
'answer': 4,
'options': [1, 2, 3, 4, 5]
},
{
'question': 'How many wheels on a bicycle',
'answer': 2,
'options': ['one', 'two', 'three', 'twenty six']
},
{
'question': 'What colour is a swan in Australia',
'answer': 1,
'options': ['black', 'white', 'pink']
}
]
for question in questions:
print (question['question'] + '?')
n = 1
for options in question['options']:
print ("%d) %s" % (n, options))
n = n + 1
response = sys.stdin.readline().strip()
if int(response) == question['answer']:
print ("CORRECT")
else:
print ("wrong")
解决方案描述
- 使用 Python 中的字典来表示问题。每个问题是一个字典,其中包含三个键值对:
question(问题)、answer(答案)和options(选项)。 - 使用一个
for循环来遍历问题列表,并打印每个问题的question和options。 - 使用
input()函数获取用户的答案并将其转换为整数。 - 根据用户的答案,判断是否正确并输出相应的提示。