Python:AttributeError:' int'对象没有属性'追加'

时间:2017-07-04 15:53:39

标签: python python-3.x

我有一个int,list的字典。我试图做的是循环“一些事情”。如果密钥存在于dict中,则将该项添加到lsit或者创建一个新列表并添加该项。 这是我的代码。

Line 27: AttributeError: 'int' object has no attribute 'append'

我的问题是双重的。 1.我收到以下错误, Line 27 is the line marked with *** var user = new Entities.User { Name = "John" }; context.Users.Add(user); context.SaveChanges(); // Reference the user created in the Administrator table context.Administradors.Add(new Entities.Administrator { UserId = user.Id }); context.SaveChanges(); 我错过了什么导致错误。

  1. 如何运行这种检查密钥的算法并更加诡异地添加到字典中的列表。

1 个答案:

答案 0 :(得分:2)

首先设置一个列表,然后使用值替换替换该列表

else:
   levels[curr_node.dist] = []
   levels[curr_node.dist].append(curr_node.tree_node.val)
   levels[curr_node.dist] = curr_node.tree_node.val

删除最后一行,它会破坏你的代码。

您可以使用dict.setdefault() method在缺少密钥时分配空列表,同时返回密钥的值,而不是使用if...else

levels.setdefault(curr_node.dist, []).append(curr_node.tree_node.val)

这一行替换了您的6 if: ... else ...行。

您还可以使用collections.defaultdict() object

from collections import defaultdict

levels = defaultdict(list)

levels[curr_node.dist].append(curr_node.tree_node.val)

对于缺失的键,会自动添加列表对象。这有一个缺点:后来的代码中有一个错误,它会意外地使用一个不存在的密钥,这会让你得到一个空列表,在调试错误时会让人感到困惑。