如何将值列表分配给列表的元素

时间:2014-11-23 19:17:48

标签: python dictionary

我想根据某些条件更改字典的值。

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

2 个答案:

答案 0 :(得分: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")

答案 1 :(得分: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,则还需要使用浮动进行划分。

如果您只想更新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"