【问题标题】:Randomly choosing variable out of a dictionary从字典中随机选择变量
【发布时间】: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


【解决方案1】:

你应该试试

import random
def battle():
    moveset_dict = {
    "1": 25, 
    "2": 50,
    "3": 75,
    "4": 100,
    }
    hp = 100

    while hp > 0 :
        attack_chosen =  random.choice(range(len(moveset_dict)))
        hp = hp - attack_chosen
        print("Alar used", attack_chosen, "Valor has", hp, "hp")

    else:
        print("Valor has fainted")

battle()

【讨论】:

    猜你喜欢
    • 2016-04-14
    • 1970-01-01
    • 2020-04-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-30
    相关资源
    最近更新 更多