我想将值列表从 0、1 和 2 转换为 2,2;1,2 和 1,1。我写了一个应该这样做的函数:
def dec2(code):
if code == 0:
ret_val = '2','2'
elif code == 1:
ret_val = '1','2'
elif code == 2:
ret_val = '1','1'
else:
ret_val = '0','0'
return ret_val
只要我在现成的列表上运行它,它似乎工作正常:
In [87]: a=[1,2,1,2]
In [88]: b=[dec2(x) for x in a]
In [89]: b
Out[89]: [('1', '2'), ('1', '1'), ('1', '2'), ('1', '1')]
但是,当我尝试使用它来替换字典值时,我得到 UnboundLocalError.:
In [82]: gtps
Out[82]: {11: [1, 2, 1, 2], 22: [2, 2, 1, 1], 33: [1, 9, 0, 2]}
[86]: for k,v in gtps.iteritems():
....: tmp=[dec2(x) for x in v]
....: all[k]=tmp
....:
....:
---------------------------------------------------------------------------
UnboundLocalError Traceback (most recent call last)
UnboundLocalError: local variable 'ret_val' referenced before assignment
有任何想法吗?