我正在閱讀新書「從頭開始學習數據科學: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