简体   繁体   English

关于从 python 中的字典中获取随机 object 的初学者问题

[英]Beginner question about getting a random object out of dictionaries in python

I recently started with LPTHW.我最近开始使用 LPTHW。 At exercise 39 I did a litle sidetracked and updated the code towards my ideas.在练习 39 中,我根据自己的想法做了一点偏离并更新了代码。 It works as intended except it picks the item out of countries in order and I'd like if it would do in random.它按预期工作,只是它按顺序从国家/地区中挑选物品,我希望它会随机进行。

Can I solve this easily or the whole thing is a dead end?我可以轻松解决这个问题还是整个事情都是死胡同? The idea is to pick a random element ask 1 of the 3 questions by random then compare if the answer is correct or not.这个想法是选择一个随机元素随机询问 3 个问题中的 1 个,然后比较答案是否正确。

图像1

图2

图3

You can use:您可以使用:

import random

random.choice(list(my_dict.keys()))

To select a random key from a dictionary.给 select 一个字典中的随机键。

Assuming that you want to loop over every item in your countries dict as you do at the moment, just in a random order instead, then you can use random.shuffle to randomly shuffle a list.假设您想像现在一样循环遍历countries地区字典中的每个项目,只是以随机顺序代替,那么您可以使用random.shuffle随机打乱列表。

So, one option would be to extract the keys of your dictionary into a list, shuffle them, and iterate over those to provide the randomness.因此,一种选择是将字典的键提取到列表中,将它们打乱,然后迭代它们以提供随机性。

Try replacing line 63 with these four lines of code instead:尝试用以下四行代码替换第 63 行:

country_keys = list(countries.keys())
random.shuffle(country_keys)
for country in country_keys:
    abbrev = countries[country]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM