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

标签 python dictionary

因此,在我的代码中,我让它从 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? Sydney
Sorry, you have entered an incorrect answer
What is the capital of England? london
Correct, you have scored
What is the capital of Indonesia? jakarta
Correct, you have scored
What is the capital of Canada? toronto
Sorry, you have entered an incorrect answer
Score: 2

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

相关文章:

Python:返回值在嵌套列表中出现的百分比更高

python - 在 Python 的 for 循环中使用 pd.get_dummies 创建虚拟变量

python - 如何使用临时文件系统在 python 中模拟 os.walk?

python - Windows中的YOLO对象检测

python - sqlalchemy 按表名和过滤条件过滤列表

Python - 字典中的递归循环

mysql - 在线词典 MySQL 的英文单词

c++ - 用于访问集合的已排序子集的数据结构 C++

swift - 如何更新混合类型的 Swift 字典值,尤其是数组

c++ - 如何将 map 作为参数传递并在此方法中添加?