我正在做《刽子手》,为了这个问题简化了我的代码
从本质上说,我试图在用户输入的字典中随机选择一个对象,无论用户选择哪个选项。例如,如果用户将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)
但我想这样做感觉没有那么“活力” 有人能帮我找出为什么这个代码不起作用,以及我如何编辑来修复它吗
只需添加另一个嵌套级别
您还可以使用字典的
.keys
方法动态地向用户呈现选择所以也许有点像
在处理嵌套数据时,它可以帮助您在遍历嵌套结构时命名变量,例如
nested = parent[key]
、more_nested = nested[other_key]
,等等。对我来说,这比obj[key][index][other_key]
更容易推理你想要另一个dict,用
hello
和hi
作为键相关问题 更多 >
编程相关推荐