TypeError:“int”对象没有属性“getitem”错误,因为b中可能有勘误

2024-06-13 07:01:45 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在翻阅新书《从头开始的数据科学:Python的第一原理》,我想我找到了一个勘误表。

当我运行代码时,我得到了"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]

我认为如何解决: 我认为您需要用户作为第二个参数,然后执行“for foaf in users[friend][“friends”]”而不是“for foaf in friend[friends”]


Tags: ofnameinfriendididsforusers
2条回答

错误开启:

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

在第二个for循环中,您试图访问__getitem__users[0]["friends"],它正好是5(int没有__getitem__)。

你想把每个朋友和每个foaf存储在列表中。问题是foaf从存储在用户上的友谊中的元组中获取数字,然后尝试从中访问,尝试从整数值调用。

这就是你问题的确切原因。

是的,你在书中发现了一段不正确的代码。

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将按预期工作。

相关问题 更多 >