others - TypeError:'int'对象没有属性'__getitem__'错误,因为可能的勘误

当我运行代码时 "TypeError: 'int' object has no attribute '__getitem__'".我认为这是因为当我尝试选择friend["friends"]时,friend是一个不能subset的整数,


users = [
 {"id": 0,"name":"Ashley"},
 {"id": 1,"name":"Ben"},
 {"id": 2,"name":"Conrad"},
 {"id": 3,"name":"Doug"},
 {"id": 4,"name":"Evin"},
 {"id": 5,"name":"Florian"},
 {"id": 6,"name":"Gerald"}
]

#create list of tuples where each tuple represents a friendships between ids
friendships = [(0,1), (0,2), (0,5), (1,2), (1,5), (2,3), (2,5), (3,4), (4,5), (4,6)]

#add friends key to each user 
for user in users:
 user["friends"] = []

#go through friendships and add each one to the friends key in users
for i, j in friendships:
 users[i]["friends"].append(j)
 users[j]["friends"].append(i)

def friends_of_friend_ids_bad(user): 
 #foaf is friend of friend
 return [foaf["id"]
 for friend in user["friends"]
 for foaf in friend["friends"]]

print friends_of_friend_ids_bad(users[0])

完全回溯:


Traceback (most recent call last):
 File"/Users/marlon/Desktop/test.py", line 57, in <module>
 print friends_of_friend_ids_bad(users[0])
 File"/Users/marlon/Desktop/test.py", line 55, in friends_of_friend_ids_bad
 for foaf in friend["friends"]]
TypeError: 'int' object has no attribute '__getitem__'
[Finished in 0.6s with exit code 1]
[shell_cmd: python -u"/Users/marlon/Desktop/test.py"]
[dir: /Users/marlon/Desktop]
[path: /usr/bin:/bin:/usr/sbin:/sbin]

时间:

是,你在本书中找到了不正确的代码。

friends_of_friend_ids_bad函数的实现应该如下所示:


def friends_of_friend_ids_bad(user): 
 #foaf is friend of friend
 return [users[foaf]["id"]
 for friend in user["friends"]
 for foaf in users[friend]["friends"]]

user["friends"]是整数的列表,因此friend是一个整数,friend["friends"]会引发TypeError异常,


看起来,书中的问题不是关于friends_of_friend_ids_bad函数,而是关于填充friends列表。

替换


for i, j in friendships:
 users[i]["friends"].append(j)
 users[j]["friends"].append(i)


for i, j in friendships:
 users[i]["friends"].append(users[j])
 users[j]["friends"].append(users[i])

然后friends_of_friend_ids_badfriends_of_friend_ids将按预期工作。

错误在:


return [foaf["id"] for friend in user["friends"] for foaf in friend["friends"]]

这就是问题的确切原因。

...