[英]How do I find a random object within a list inside of a dictionary?
I'm working on doing hangman and have simplified my code for the sake of the question. 我正在做hangman,为了这个问题简化了我的代码。
Essentially I am trying to randomly select within a dictionary which is inputted by the user, a random object within whichever option the user chooses. 本质上,我试图在用户输入的字典中随机选择一个随机对象,无论用户选择哪个选项。 For example if the user put a for the categ, and FIRST for the opt, randomOpt would be set to either a, b, or c. 例如,如果用户为categ放置a,为opt放置FIRST,则randomOpt将设置为a,b或c。
categ = input('hello OR hi: ')
opt = input('FIRST, SECOND, OR LAST: ')
hello = {'FIRST':['a','b','c'],'SECOND':['z','x','y'],'LAST':['t','u','v']}
hi = {'FIRST':[1, 2, 3], 'SECOND':[20, 19, 18], 'LAST': [10, 11, 12]}
import random
randomOpt = random.choice(categ[opt])
print(randomOpt)
Whenever I run this, Python returns 'string indices must be integers' My friend suggested doing 每当我运行此命令时,Python都会返回“字符串索引必须为整数”,我的朋友建议这样做
categ = input('hello OR hi: ')
opt = input('FIRST, SECOND, OR LAST: ')
hello = {'FIRST':['a','b','c'],'SECOND':['z','x','y'],'LAST':['t','u','v']}
hi = {'FIRST':[1, 2, 3], 'SECOND':[20, 19, 18], 'LAST': [10, 11, 12]}
import random
if categ == 'hello':
randomOpt = random.choice(hello[opt])
elif categ == 'hi':
randomOpt = random.choice(hi[opt])
print(randomOpt)
But doing so feels a lot less 'dynamic' I suppose Could anybody help me figure out why this code doesn't work, and how I could edit to to fix it? 但是我认为这样做的“动态性”要小得多,有人可以帮助我弄清楚为什么这段代码不起作用,以及如何编辑以解决该问题吗?
You want another dict, with hello
and hi
as keys. 您需要另一个以hello
和hi
为键的字典。
stuff = {
'hello': hello,
'hi': hi
}
randomOpt = random.choice(stuff[categ][opt])
Just add another level of nestedness. 只需添加另一级别的嵌套即可。
choices = {'hello': hello,
'hi': hi
}
You can also use the .keys
method of dictionaries to dynamically present the choices to the user. 您还可以使用字典的.keys
方法向用户动态显示选择。
So perhaps something like 所以也许像
user_choice = input('Choose one: ' + ' '.join(choices.keys())
choice = choices[user_choice]
options = ' '.join(choice.keys())
user_opt = input('Choose one: ' + options)
population = choice[user_opt]
print(random.choice(population))
When dealing with nested data, it can help to name variables as you traverse nested structures, IE nested = parent[key]
, more_nested = nested[other_key]
, etc. which is, to me, easier to reason about compared to obj[key][index][other_key]
处理嵌套数据时,它可以帮助您遍历嵌套结构时命名变量,例如IE nested = parent[key]
, more_nested = nested[other_key]
等。在我看来,与obj[key][index][other_key]
相比more_nested = nested[other_key]
更容易推理obj[key][index][other_key]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.