【问题标题】:Random.choice isn't workingRandom.choice 不起作用
【发布时间】:2016-12-17 17:08:31
【问题描述】:

我将 random.choice 与字典一起使用,但它不起作用。此错误显示为 AttributeError: 'function' 对象在 main.py 的第 90 行没有属性 'choice'

(提前做好课程)

items = {"Weak Leather Boots": Item("Weak Leather Boots", 1, "Armour"),"Health Potion":Item("Health Potion", 5, "Medicine" ), "Iron Fist":Item("Iron Fist" , 5, "Weapon"), "Speed Shoes":Item("Speed Shoes", 10, "Armour"),"Gold":randint(1, 50), "Ice Wand":Item("Ice Wand", 20, "Weapon") }
def Loot(lvl):
  choose = random(items.values())

  if choose.rarity > lvl:
    choose = randint(items.values())

  else:
    print "You have found a " + choose.name
    if type(choose) is int:
        player.gold += choose

    else:
        player.inventory.append(choose.name)

【问题讨论】:

  • 您粘贴的代码中似乎没有使用random.choice。但是,第一个猜测是您在某处调用了函数random,并覆盖了对模块的引用
  • 这个问题无法重现,因为你没有告诉我们你是如何导入random模块或者你如何调用random.choice。您应该能够编写一个仅几行的小示例程序来演示该问题。

标签: python dictionary


【解决方案1】:

在代码的开头你应该随机导入

import random

然后这样称呼它:

random.randint(something)

或:

random.choice(something)

或者如果你愿意,你可以只导入 randint 和选择:

from random import randint,choice

然后你就可以写了:

randint(something)
choice(something)

如果您想了解有关随机模块的更多信息,请参阅文档链接:https://docs.python.org/3/library/random.html

【讨论】:

    猜你喜欢
    • 2021-06-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-16
    • 2010-11-24
    • 1970-01-01
    • 1970-01-01
    • 2019-10-10
    相关资源
    最近更新 更多