如何在Python中对应两个列表

2024-09-29 19:15:08 发布

您现在位置:Python中文网/ 问答频道 /正文

让我们想象一下我有:

question_list = ['how old are you?', 'how tall are you']
possible_answers = ['15, 14, 19, 32', '1.92cm, 2.01cm, 1.59cm, 1.72cm']

我希望能够将“你多大了?”与“15、14、19、32”相对应,所以当我随机打印问题列表中的一个问题时,我会从可能的答案中得到相应的答案。我该怎么做

我被困在这里的背景:

if random.choice(game_list) == 'trivia':
 question = print(random.choice(question_list))

本质上,我想把一个列表中的某个东西和另一个列表中的另一个东西对应起来


Tags: 答案you列表cmrandomoldarelist
2条回答

使用zip将它们压缩在一起:

questions_and_answers = list(zip(question_list, possible_answers))

# later when getting an answer
question, answers = random.choice(questions_and_answers)
print("The question is:", question)
print("The possible answers are:", answers)

如果要将答案作为列表,请使用逗号拆分:

answers_list = answers.split(", ")

您的标题方向错误,因为print()没有返回任何内容,您需要使用一个变量来存储索引,因为它必须使用两次

if random.choice(game_list) == 'trivia':
    # get random index for question
    question_num = random.randint(0, len(question_list)-1)
    # print question
    print(question_list[question_num])
    # print corresponding answer
    print(possible_answers[question_num])

相关问题 更多 >

    热门问题