2015-06-15 175 views
0
grammar = { 
'expert' : { 
'min_time' : 30, 
'filtered_thresholds' : {'A':10,'B':10,'C':10,'D':10,'E':20,'I':10,'T':10,'H':10,'K':0,'J':0,'L':0,'M':0,'N':0,'O':0,'P':0,'Q':0,'R':0,'S':0}, 
'filter_screens' : ['H','I','J','K','L','M','N','O','P','Q','R','S'] 
}, 

'expert2' : { 
'min_time' : 2, 
'filtered thresholds' : {'A':10,'B':10,'C':10,'D':10,'E':20,'I':10,'T':10,'H':10,'K':0,'J':0,'L':0,'M':0,'N':0,'O':0,'P':0,'Q':0,'R':0,'S':0}, 
'filter screens' : ['H','I','J','K','L','M','N','O','P','Q','R','S'] 
} 
} 
for i in grammar: 
    for j in grammar[i]: 
     min_time = j['min_time'] 
     filtered_thresholds_expert = j['filtered_thresholds'] 
     filtered_screens = j['filtered_screens'] 
     ProcessThresholds(time_per_screen_percentage) 

我想「MIN_TIME」分配給MIN_TIME,「filtered_thresholds」來filtered_thresholds_expert和「filtered_screens」到filtered_screens。
然而,我得到這個錯誤
分配字典鍵的值給另一個變量

min_time = j['min_time']
TypeError: string indices must be integers, not str

回答

1

你不需要內循環。

for i in grammar: 
    j = grammar[i] 
    min_time = j['min_time'] 
    filtered_thresholds_expert = j['filtered_thresholds'] 
    filtered_screens = j['filtered_screens'] 
    ProcessThresholds(time_per_screen_percentage) 

而且可以進一步將其打磨至

for key, j in grammar.iteritems(): 
    ... 
1

你不需要嵌套循環存在。你最終迭代你的內部字典的鍵,所以當你到達錯誤行時,j只是字符串'min_time'而不是那個字典條目。我修正了一下你的代碼,所以它不會在你的密鑰中混合使用空格和下劃線。看看這是否適合你。

grammar = { 
'expert' : { 
'min_time' : 30, 
'filtered_thresholds' : {'A':10,'B':10,'C':10,'D':10,'E':20,'I':10,'T':10,'H':10,'K':0,'J':0,'L':0,'M':0,'N':0,'O':0,'P':0,'Q':0,'R':0,'S':0}, 
'filter_screens' : ['H','I','J','K','L','M','N','O','P','Q','R','S'] 
}, 

'expert2' : { 
'min_time' : 2, 
'filtered_thresholds' : {'A':10,'B':10,'C':10,'D':10,'E':20,'I':10,'T':10,'H':10,'K':0,'J':0,'L':0,'M':0,'N':0,'O':0,'P':0,'Q':0,'R':0,'S':0}, 
'filter_screens' : ['H','I','J','K','L','M','N','O','P','Q','R','S'] 
} 
} 
for i in grammar: 
    j = grammar[i] 
    min_time = j['min_time'] 
    filtered_thresholds_expert = j['filtered_thresholds'] 
    filtered_screens = j['filter_screens'] 
    ProcessThresholds(time_per_screen_percentage) 
1

你有幾個問題:

首先,有沒有明顯的理由grammar是一本字典:你迭代,但從不索引它的關鍵,所以它可能是一個列表。其次,你只需要一個循環。試試這個:

grammar = [ 
{ 
'min_time' : 30, 
'filtered_thresholds' : {'A':10,'B':10,'C':10,'D':10,'E':20,'I':10,'T':10,'H':10,'K':0,'J':0,'L':0,'M':0,'N':0,'O':0,'P':0,'Q':0,'R':0,'S':0}, 
'filter_screens' : ['H','I','J','K','L','M','N','O','P','Q','R','S'] 
}, 

{ 
'min_time' : 2, 
'filtered thresholds' : {'A':10,'B':10,'C':10,'D':10,'E':20,'I':10,'T':10,'H':10,'K':0,'J':0,'L':0,'M':0,'N':0,'O':0,'P':0,'Q':0,'R':0,'S':0}, 
'filter screens' : ['H','I','J','K','L','M','N','O','P','Q','R','S'] 
} 
] 

for i in grammar: 
    min_time = i['min_time'] 
    filtered_thresholds_expert = i['filtered_thresholds'] 
    filtered_screens = i['filter_screens'] 
    ProcessThresholds(time_per_screen_percentage) 
相關問題