2011-03-06 52 views
5

我構建了我的應用程序的一個快速部分,它查看用戶的追隨者,並突出顯示用戶追隨的人(朋友)跟隨的內容。顯示Twitter追隨者跟隨在Python/Django中的朋友

我想知道兩件事情:

  1. 有沒有更有效的方式來做到這一點?似乎這樣會激起Twitter的API限制,因爲我需要檢查每個用戶的朋友的朋友。

  2. 這是創建一個包含朋友ID和他們關注的追隨者的字典列表。相反,字典會更好,跟隨者ID,然後跟隨他們的朋友。提示?

代碼:

# Get followers and friends 
followers = api.GetFollowerIDs()['ids'] 
friends = api.GetFriendIDs()['ids'] 

# Create list of followers user is not following 
followers_not_friends = set(followers).difference(friends) 

# Create list of which of user's followers are followed by which friends 
followers_that_friends_follow = [] 
for f in friends: 
    ff = api.GetFriendIDs(f)['ids'] 
    users = followers_not_friends.intersection(ff) 
    followers_that_friends_follow.append({'friend': f, 'users': users }) 

回答

1

對於你的問題的第二部分:

import collections 

followers_that_friends_follow = collections.defaultdict(list) 
for f in friends: 
    ff = api.GetFriendsIDs(f)['ids'] 
    users = followers_not_friends.intersection(ff) 
    for user in users: 
     followers_that_friends_follow[user].append(f) 

,這將導致一個詞典:下面的

鍵= IDS的追隨者用戶,用戶不關注,用戶朋友跟隨。

值=的後面跟隨的朋友ID的列表,用戶不遵循

例如,如果用戶的跟隨者有23的ID和兩個用戶的朋友(用戶16和用戶28 )按照用戶23,使用鍵23應該給出以下結果

>>> followers_that_friends_follow[23] 
[16,28]