我在我正在使用的函数中使用类似的方法。当我尝试这样做时,为什么会出现重大错误?将多个值添加到字典中的一个键与for循环
def trial():
adict={}
for x in [1,2,3]:
for y in [1,2]:
adict[y] += x
print(adict)
我在我正在使用的函数中使用类似的方法。当我尝试这样做时,为什么会出现重大错误?将多个值添加到字典中的一个键与for循环
def trial():
adict={}
for x in [1,2,3]:
for y in [1,2]:
adict[y] += x
print(adict)
当您第一次使用它时,没有将值分配给adict[y]
。
def trial():
adict={}
for x in [1,2,3]:
for y in [1,2]:
if y in adict: # Check if we have y in adict or not
adict[y] += x
else: # If not, set it to x
adict[y] = x
print(adict)
输出:
>>> trial()
{1: 6, 2: 6}
你应该修改这样的youre代码:
def trial():
adict={0,0,0}
for x in [1,2,3]:
for y in [1,2]:
adict[y] += x
print(adict)
“adict” 会没有入口。所以adict [1]失败,因为它正在访问一个不存在的变量。
您没有初始化每个密钥的adict
。您可以使用defaultdict
来解决这个问题:
from collections import defaultdict
def trial():
adict=defaultdict(int)
for x in [1,2,3]:
for y in [1,2]:
adict[y] += x
print(adict)
trial()
结果是defaultdict(<class 'int'>, {1: 6, 2: 6})
您尝试添加的东西'adict [Y]'和'adict [Y] + = x',但'adict [ y]'在第一次尝试访问密钥时未定义。 – Matthias