【问题标题】:append item to list at a random index os initial list将项目附加到随机索引处的列表 os 初始列表
【发布时间】:2017-12-07 20:08:12
【问题描述】:

我有一个我正在做的测验的答案列表,我想使它成为多项选择,并且在多项选择测验中,答案永远不会总是在底部或在相同的索引中,但这就是我的代码

Answers = ["bogota", "carracas", "brasilia", "santiago", "london"]
Questions = ["colombia", "venezuela", "brasil", "chile", "england"]
q = [Questions[i] for i in sorted(random.sample(range(len(Questions)), 3))]
tryindex = [i for i, x in enumerate(QuestionsT) if x in q]
Ca = [Answers[i] for i in tryindex]
for x in q:
    Pa = [i for i in random.sample(Answers, 3) if i !=q.index(x)]
    Pa.append(Ca[q.index(x)])
    print("what is the capital of:" + x + "?")
    print("\n".join(Pa))
    a = input("\n""Answer")
    for i in range(0,3):
        if a == Ca[i]:
            score +=1

这会返回例如一次迭代: 哥伦比亚的首都是哪里? 伦敦 卡拉卡斯 巴西利亚 圣地亚哥 波哥大

请注意,由于 .append(Ca[q.insert(x)]),波哥大位于底部

我想要的是这种情况下的答案将随机插入到 Ca(正确答案)中。有没有办法做到这一点?

  • 答案是指所有可能的答案的一般列表 表示所有可能问题的一般列表

    • 在上述两个列表中,每个元素都是通过其索引引用的,所以
      通过在问题中找到元素的索引,它是 可以通过相同的索引找到答案中保存的值

    q 表示为测验随机选择的问题 Ca 表示 q 中问题的正确答案。 Pa 表示可能的答案,从一般数组 Answers 中随机获得。

【问题讨论】:

  • 不要使用索引。要么将压缩的 q & a 随机化,要么创建一个 dict question => answer。
  • 您的问答列表没有引号。代码不起作用

标签: python list random


【解决方案1】:

这是一个干净的解决方案,看看,改变你想要的,问你没有得到的。

# -*- coding: utf-8 -*-

# Imports
import random

# Parameters
data = {'Brasil': 'Brasilia',
 'Chile': 'Santiago',
 'Colombia': 'Bogota',
 'England': 'London',
 'Venezuela': 'Carracas'}

nbr_questions = 3
score = 0
former_questions = ['']

# Script
for i in range(nbr_questions):
    # Grab the couple country / capital from the data dictionnary
    capital = ''
    while capital in former_questions:
        country, capital = random.choice(list(data.items()))

    # Create the proposition display list
    proposition_display = list()
    proposition_display.append(capital)
    i = 0
    while i < 2:
        cap = random.choice(list(data.values()))
        if cap not in proposition_display:
            proposition_display.append(cap)
            i += 1

    # Display
    print ('What is the capital of {} ?'.format(country))
    answer = input ('Answer: ')

    if answer.lower().strip(' ') == capital.lower().strip(' '):
        print ('Correct!')
        score += 1
    else:
        print ('Wrong. Answer was {}.'.format(capital))

    print ('-----------------------------')

    # Add this capital to the list former_questions to avoid repetition
    former_questions.append(capital)

print ('Your score is: {}'.format(score))

【讨论】:

    猜你喜欢
    • 2017-09-20
    • 2018-08-20
    • 2011-10-12
    • 1970-01-01
    • 1970-01-01
    • 2020-11-23
    • 2015-09-21
    • 2011-05-15
    • 2021-07-30
    相关资源
    最近更新 更多