2014-11-23 52 views
1

我想根據某些條件更改字典的值。如何將值列表分配給列表元素

mydic = {"10": [1, 2, 3], "20": [2, 3, 4, 7]}  
key = mydic.keys()  
val = mydic.values()  
aa = [None] * len(key) 
for i in range(len(key)): 
    for j in range(len(val[i])):  
     if val[i][j] <= 5: 
      aa[i][j] = int(math.ceil(val[i][j]/10)) 
     else: 
      aa[i][j] = "f" 

錯誤:

TypeError: 'NoneType' object does not support item assignment 

回答

0

,如果你是在價值觀只是有興趣剛剛超過mydic.itervalues()循環:

import math 

mydic = {"10": [1, 2, 3], "20": [2, 3, 4, 7]} 

aa = [[] for _ in mydic] 
for i, v in enumerate(mydic.itervalues()): # mydic.values() -> python 3 
    for ele in v: 
     if ele <= 5: 
      aa[i].append(int(math.ceil(ele/10.0))) # 10.0 for python2 
     else: 
      aa[i].append("f") 
print(aa) 

如果你正在使用Python 2,你還需要使用浮點數來劃分。

如果你只是想更新字典忘掉所有的名單,只是直接更新:

for k,v in mydic.iteritems(): # .items() -> python 3 
    for ind, ele in enumerate(v): 
     if ele <= 5: 
      mydic[k][ind] = (int(math.ceil(ele/10.))) 
     else: 
      mydic[k][ind] = "f" 
0

問題是這一行:

aa = [None] * len(key) 

這:

if val[i][j] <= 5: 
    aa[i][j] = int(math.ceil(val[i][j]/10)) 
else: 
    aa[i][j] = "f" 

當你初始化aa,將它設置爲[None, None] 。 所以,當你說aa[i][j],你是說None[j],這當然是無效的。

我想你正在嘗試做的可以這樣做:

aa = [] 
for index1, value in enumerate(mydic.values()): 
    aa.append([]) 
    for index2, item in enumerate(value): 
     if item <= 5: 
      aa[index1].append(int(math.ceil(item/10))) 
     else: 
      aa[index1].append("f") 
+0

非常感謝! – Franco 2014-11-23 19:53:12

相關問題