【发布时间】:2020-04-06 13:24:05
【问题描述】:
我试图让 python 从我的字典中选择一个随机变量在代码中运行,但似乎无法获得正确的语法。如果有人可以提供帮助,那就太好了。
def battle():
moveset_dict = {
"1": 25,
"2": 50,
"3": 75,
"4": 100,
}
hp = 100
while hp > 0 :
attack_chosen = random.range(len(moveset_dict))
hp = hp - attack_chosen
print("Alar used", attack_chosen, "Valor has", hp, "hp")
else:
print("Valor has fainted")
battle()
【问题讨论】:
-
试试
random.choice(moveset_dict.keys()) -
@dcg:
random.choice(list(moveset_dict)),因为choice需要一个序列,而.keys()返回一个迭代器。 (另外,OP,你大概想要hp -= moveset_dict[attack_chosen]) -
@Amadan 你说得对。
-
我得到 TypeError: 'dict_keys' object is not subscriptable
-
查看@Amadan 评论
标签: python python-3.x dictionary random