我正在阅读新书“从头开始学习数据科学:Python的第一原理”,我想我已经发现了勘误。TypeError:'int'对象没有属性'__getitem__'错误,因为书中可能有错误
当我运行代码我得到"TypeError: 'int' object has no attribute '__getitem__'".
我认为这是因为当我尝试选择friend["friends"]
时,friend
是一个整数,我不能子集。那是对的吗?我如何继续练习以获得理想的输出?它应该是朋友的朋友列表(foaf)。我知道有重复的问题,但这些都是固定以后...
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]
如何,我认为它可以是固定的: 我认为你需要的用户为第二个参数,然后“在网友[朋友]为FOAF [”朋友“]”,而不是“为朋友FOAF [”朋友“]做
发布完整回溯你得到了 – Alik
@Alik我添加了它 – megashigger
那里有什么“友谊”? – itzMEonTV