更新多个列表索引时在python中进行循环?

时间:2019-02-11 00:30:48

标签: python list for-loop indexing

我是python的新手。我已经完成了包含15个问题的测验的程序,从15个问题中随机选出5个,并逐一向用户打印问题。每个问题有4个可能的答案。

程序运行正常,但我不想为每个问题编写代码块,而是想遍历所有5个随机问题,并使它与每个问题的每个代码块做相同的事情。我已经习惯了Java,但看起来却不太一样,因此我评论了在for循环中的较差尝试。

我只是想使其效率更高,因此任何提示或指导都将有所帮助。我不要求对我的问题作完整答复。谢谢

#Print statement displaying a welcome message
print("***WELCOME TO THE RANDOM QUIZ***\n")

#Importing random library to use the random module
import random

#Creates a list with all 15 questions
questions = ['What is the capital city of Ireland?', 'What is the capital city of France?',
            'What is the capital city of Germany?', 'What is the capital city of Romania?',
            'What is the capital city of Russia?', 'What is the capital city of Belgium?',
            'What is the capital city of Switzerland?','What is the capital city of Egypt?',
            'What is the capital city of Japan?','What is the capital city of China?',
            'What is the capital city of Thailand?','What is the capital city of Brazil?',
            'What is the capital city of Argentina?','What is the capital city of Bolivia?',
            'What is the capital city of Mexico?']

#Creates a list with the answers for each of the 15 individual questions
possible_answers = ['a) Portlaoise | b) Waterford | c) Dublin | d) Galway ', 'a) Paris | b) Lyon | c) Nantes | d) Tolouse ',
                    'a) Frankfurt | b) Munich | c) Berlin | d) Dusseldorf ', 'a) Bucharest | b) Constanta | c) Galati | d) Sibiu ',
                    'a) Moscow | b) St.Petersburg | c) Novosirbirsk | d) Sochi ', 'a) Ghent | b) Bruges | c) Brussels | d) Antwerp ',
                    'a) Zurich | b) Geneva | c) Basel | d) Bern ', 'a) Cairo | b) Alexandria | c) Luxor | d) Giza ',
                    'a) Osaka | b) Yokohama | c) Nagoya | d) Tokyo ', 'a) Beijing | b) Shenzhen | c) Shanghai | d) Fuangzhou ',
                    'a) Bangkok | b) Chiang Mai | c) Pattaya | d) Hat Yai ', 'a) Rio de Janeiro | b) Sao Paolo | c) Salvador | d) Brasilia ',
                    'a) Mendoza | b) Rosario | c) Buenos Aires | d) Cordoba ', 'a) Santa Cruz de la Sierra | b) La Paz | c) El Alto | d) Oruro ',
                    'a) Mexico City | b) Guadalajara | c) Tijuana | d) Merida ']

#Creates a list with the right answers for each of the 15 individual questions
answers = ["Dublin","Paris","Berlin","Bucharest","Moscow","Brussels","Bern","Cairo","Tokyo","Beijing","Bangkok",
            "Brasilia","Buenos Aires","La Paz","Mexico City"]

#Creates variable and assigns the value of 5 which represents the number of random questions we need out of the possible 15
num_of_rand_q = 5

#This variable is created to keep track of the number of right answers by the user
right_q_count = 0

#Assign randomly selected question to a variable
list_of_rand_q = random.sample(questions, num_of_rand_q)


"""
In this operation we match the randomly selected question with the same question in the 'questions' list
to get its original index and assign the index value to a variable. This will help us later on to get the
answer of the exact question by using its original index value as indexes of each question and respective
answer match in both 'questions' and 'answers' lists. We do this for all 5 randomly selected questions.
"""
q_one_index = questions.index(list_of_rand_q[0])
q_two_index = questions.index(list_of_rand_q[1])
q_three_index = questions.index(list_of_rand_q[2])
q_four_index = questions.index(list_of_rand_q[3])
q_five_index = questions.index(list_of_rand_q[4])

"""
#Creating list of indexes so we can loop through them 
q_indexes = [q_one_index, q_two_index, q_three_index, q_four_index, q_five_index]

#Attempted for loop
i = 0
for i in list_of_rand_q[i]:
    print(list_of_rand_q[i])
    print(possible_answers[questions.index(list_of_rand_q[i])], "\n")
    answer_1 = input("Type the city name of which you think it's the capital! \n")

    if answer_1 in answers:
        print('Well done! This is the right answer!')
        right_q_count += 1
    else:
        print('It is the wrong answer...The right answer is actually : ', answers[q_indexes[i]])
"""


#First Question and same as other 4
#Print statement to ask the random question
print(list_of_rand_q[0])
#Print statement to display all 4 possible answers respective to the question
print(possible_answers[questions.index(list_of_rand_q[0])], "\n")
#We ask the user to type the capital city and store the user's input in the answer variable
answer = input("Type the city name of which you think it's the capital! \n")

#If statement checks if user's input matches the value in the answers list
if answer in answers:
    #If statement is true prints a message
    print('Well done! This is the right answer!\n')
    #right_q_count variable stores the number of right answers and we increment it everytime the answer given is right
    right_q_count += 1
#If the if statement is not true and user gets wrong answer then perform 'else'
else:
    #Prints a message and tells the user which is the right answer
    print('It is the wrong answer...The right answer is actually : ', answers[q_one_index], "\n")


#Print statement tells the user how many questions he got right out of the possible 5
print("You got ", right_q_count , "answers right out of 5!" )

2 个答案:

答案 0 :(得分:1)

您应该zip将三个列表一起使用,以同时遍历它们。另外,您应该对压缩列表执行random.sample,以避免进行过多索引。通常,对.index的许多调用都是代码气味。

triplets = list(zip(questions, possible_answers, answers)

num_of_rand_q = 5
right_q_count = 0
list_of_rand_q = random.sample(triplets, num_of_rand_q)

for question, choices, answer in list_of_rand_q:
    print(question)
    print(choices, "\n")

    guess = input("Type the city name of which you think it's the capital! \n")

    if guess == answer:
        print('Well done! This is the right answer!\n')
        right_q_count += 1
    else:
        print('It is the wrong answer...The right answer is actually : ', answer, "\n")

print("You got ", right_q_count , "answers right out of 5!" )

如您所见,它也更加直观,因为您不需要执行所有下标操作。

答案 1 :(得分:0)

您的for循环应如下所示:

for question in list_of_rand_q:
    print(question)

或在其他情况下:

sum = 0
for number in range(0,n):
    sum = sum + number

在python中,第一个变量(在上述情况下为问题或数字)是对象的临时名称,因为for循环遍历第二个结构(list_of_rand_q或range)。

换句话说,由于for循环已经找到并创建了对该问题的临时引用,因此在打印问题时无需在列表中给出问题的索引。