Python random.choice从作为列表的字典值中选择时不起作用

Python random.choice从作为列表的字典值中选择时不起作用,python,dictionary,random,Python,Dictionary,Random,我正在做一个程序,随机地创造一个对某件事有影响的神,以及对与原作相关的事有影响的神。有关部分包括: spheres = {'death': ['death', 'corpses', 'skulls', 'rot', 'ruin', 'the end']} # Dictionary of the things gods have power over and the relevant things to do with them class God(object): def __init_

我正在做一个程序,随机地创造一个对某件事有影响的神,以及对与原作相关的事有影响的神。有关部分包括:

spheres = {'death': ['death', 'corpses', 'skulls', 'rot', 'ruin', 'the end']}
# Dictionary of the things gods have power over and the relevant things to do with them

class God(object):

  def __init__(self, sphere, associations, name):
    self.sphere = sphere
    self.associations = accociations
    self.name = name
# Chooses areas to have power over, hopefully making it less and less likely as the program goes on further      
  def get_association(self):
    chance_of_association = 0
    list_of_choices = []
    while random.randint(0, chance_of_association) == 0:
      choice = random.choice(list(spheres[self.sphere]))
      # this is the problem
      if random.randint(1, 2) == 1:
        chance_of_association += 1
      list_of_choices.append(choice)
    self.associations = list_of_choices

deity1 = God(random.choice(spheres), deity1.get_association, 'godname')
当我运行此程序时,我得到:

  File "program.py", line 22, in <module>
    deity1 = God(random.choice(spheres), deity1.get_association, 'godname')
  File "/opt/python-3.6/lib/python3.6/random.py", line 258, in choice
    return seq[i]
KeyError: 0
文件“program.py”,第22行,在
Detiy1=神(随机选择(球体),Detiy1.get_关联,“神名”)
文件“/opt/python-3.6/lib/python3.6/random.py”,第258行,在选项中
返回序号[i]
关键错误:0

即使行中没有list(),也会产生相同的错误。我怎样才能得到它

您可以根据需要更改线路

deity1 = God(random.choice(spheres['death']), deity1.get_association, 'godname')
但这也会导致另一个错误,因此请再次查看您的代码

Traceback (most recent call last):
File "<input>", line 23, in <module>
NameError: name 'deity1' is not defined
回溯(最近一次呼叫最后一次):
文件“”,第23行,在
NameError:未定义名称“Detiy1”

您可以将行更改为

deity1 = God(random.choice(spheres['death']), deity1.get_association, 'godname')
但这也会导致另一个错误,因此请再次查看您的代码

Traceback (most recent call last):
File "<input>", line 23, in <module>
NameError: name 'deity1' is not defined
回溯(最近一次呼叫最后一次):
文件“”,第23行,在
NameError:未定义名称“Detiy1”
在实例化过程中,您不能引用“diety1”并调用其方法“get_association”,因为对象尚未创建。因此,我们将方法调用移动到运行
\uuuu init\uuu
时。我们不得不更改random.choice来搜索字典中的键列表

deity1 = God(random.choice(list(spheres.keys())), 'godname')
在实例化过程中,您不能引用“diety1”并调用其方法“get_association”,因为对象尚未创建。因此,我们将方法调用移动到运行
\uuuu init\uuu
时。我们不得不更改random.choice来搜索字典中的键列表

deity1 = God(random.choice(list(spheres.keys())), 'godname')

你的意思是随机选择(球体['death'])?如果不是,请解释你想做什么。(您正在将一个
dict
传递给
random.choice
,这没有真正意义。)您是指
random.choice(球体['death'])
?如果不是,请解释您试图做什么。(您正在将一个
dict
传递给
random.choice
,这没有什么意义。)谢谢,这个解释很有意义