如何在字典的列表中找到随机对象?

2024-09-30 10:40:04 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在做《刽子手》,为了这个问题简化了我的代码

从本质上说,我试图在用户输入的字典中随机选择一个对象,无论用户选择哪个选项。例如,如果用户将a作为categ,并首先作为opt,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)

每当我运行此命令时,Python都会返回“string index must be integers” 我的朋友建议我做

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)

但我想这样做感觉没有那么“活力” 有人能帮我找出为什么这个代码不起作用,以及我如何编辑来修复它吗


Tags: or代码用户importhelloinputrandomhi
2条回答

只需添加另一个嵌套级别

choices = {'hello': hello,
           'hi': hi
}

您还可以使用字典的.keys方法动态地向用户呈现选择

所以也许有点像

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))

在处理嵌套数据时,它可以帮助您在遍历嵌套结构时命名变量,例如nested = parent[key]more_nested = nested[other_key],等等。对我来说,这比obj[key][index][other_key]更容易推理

你想要另一个dict,用hellohi作为键

stuff = {
    'hello': hello,
    'hi': hi
}

randomOpt = random.choice(stuff[categ][opt])

相关问题 更多 >

    热门问题