2017-10-07 20 views
1

我正在製作一個程序,隨機制作一個影響事物的上帝,並影響與原文相關的事物。相關配件有:random.choice當從字典中選擇一個值列表時不起作用

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 

即使沒有它產生同樣的錯誤就行了列表()。我怎樣才能得到它

+0

你的意思是'random.choice(spheres ['death'])'? – smarx

+2

如果不是,請解釋你正在嘗試做什麼。 (你正在向'random.choice'傳遞一個'dict',這沒有任何意義。) – smarx

回答

2
import 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__(self, sphere, name, associations = None): 
    self.sphere = sphere 
    #so associations are not allocated twice 
    self.possible_associations = spheres[self.sphere] 
    self.associations = associations 
    self.get_association() 
    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 and self.possible_associations: 
     choice = random.choice(self.possible_associations) 
     self.possible_associations.remove(choice) 
     if random.randint(1, 2) == 1: 
     chance_of_association += 1 
     list_of_choices.append(choice) 
    self.associations = list_of_choices 

不能引用「diety1」,並調用它的方法,「get_association」,實例化過程中,因爲對象尚未建立。因此,我們將方法調用移至__init__運行時發生。我們必須改變random.choice來搜索字典中的鍵列表。

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

謝謝,這個解釋很有意義 –

2

可以更改行

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 
相關問題