2014-11-23 4 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) 

하는 경우 당신은 파이썬 2를 사용하고있다. 또한 나눗셈을 위해 float을 사용해야 할 것이다.

그냥 DICT 모든 목록을 잊어 그냥 직접 업데이트 업데이트하려면 :

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) 

이 : 당신이 aa을 초기화 할 때

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

, 당신은 [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

관련 문제