gpt4 book ai didi

Python - 我需要从字典中删除实例吗?

转载 作者:行者123 更新时间:2023-12-01 04:19:26 24 4
gpt4 key购买 nike

因此,在我的代码中,我让它从 CSV 文件中的 2 行创建一个字典,这非常有效。

但是,我根据字典的长度范围从字典中随机选出一个问题。基本上,我想知道,我是否需要从字典中删除/删除这个实例(问题),因为我已经使用了它,因为它可以再次将其随机化,或者字典不会将字符串随机化两次?

如果我确实需要删除它,我该怎么做,

import csv
import random
score = 0
# Open file and read rows 0 and 1 into dictionary.
capital_of = dict(csv.reader(open('GeogDatacsv.csv')))
for i in range(len(capital_of)):
questionCountry = random.choice(list(capital_of.keys()))
answer = capital_of[country]
guess = input("What is the capital of %s? " % country)
print(answer)
if guess == answer:
print("Correct, you have scored")
score +=1
else: print('Sorry, you have entered an in correct answer')

谢谢

最佳答案

您可以通过应用random.sample()来做到这一点,而不会破坏您的字典。在字典的项目上,将 k 设置为字典的长度。这将以随机顺序返回字典中的项目列表,然后您可以对其进行迭代。

import random

capital_of = {'Australia':'Canberra',
'England':'London',
'Indonesia':'Jakarta',
'Canada':'Ottawa',}

score = 0
for country, capital in random.sample(capital_of.items(), len(capital_of)):
guess = input("What is the capital of %s? " % country)
if guess.lower() == capital.lower():
print("Correct, you have scored")
score +=1
else:
print('Sorry, you have entered an incorrect answer')

print("Score: {}".format(score))

示例输出

What is the capital of Australia? SydneySorry, you have entered an incorrect answerWhat is the capital of England? londonCorrect, you have scoredWhat is the capital of Indonesia? jakartaCorrect, you have scoredWhat is the capital of Canada? torontoSorry, you have entered an incorrect answerScore: 2

关于Python - 我需要从字典中删除实例吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33880758/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com