How to speed up this code? On average, work takes about 4 minutes for a group of 300 people. I think the thing is in the entry of groups in the dictionary. Is there any more rational way to do this?
This code takes all the subscribers of a particular group (in this case, fineline_official), then checks with each subscriber what groups it consists of groups = api.users.getSubscriptions(user_id = mid)['groups'] . Then it adds the id of these groups to the dictionary. If the dictionary does not contain an id of any group, then it adds it there groups_dict[gid] = 1 . If the id of this group is already in the dictionary, then it adds 1 to the key value. At the entrance we get a group (id), at the output of the 10 most popular groups among the subscribers of this group
import vk session = vk.Session(access_token='token') #VK token api = vk.API(session) group_id = 'fineline_official' #group id group_stat=api.groups.getMembers(group_id = group_id ) #ΠΠΎΠ»ΡΡΠ°Π΅ΠΌ ΡΡΠ°ΡΡΠ½ΠΈΠΊΠΎΠ² Π³ΡΡΠΏΠΏΡ members_id = group_stat['users'] members_count = group_stat['count'] groups_dict = {} if members_count <= 1000: for mid in members_id: try: groups = api.users.getSubscriptions(user_id = mid)['groups'] groups_id = groups['items'] for gid in groups_id: try: groups_dict[gid] groups_dict[gid] += 1 except: groups_dict[gid] = 1 except: continue else: print('>1000') lst = [] for k in groups_dict.items(): #ΠΠΎΠ±Π°Π²Π»Π΅Π½ΠΈΠ΅ Π² ΡΠΏΠΈΡΠΎΠΊ ΠΊΠΎΡΡΠ΅ΠΆ ΠΈΠ· id Π³ΡΡΠΏΠΏΡ ΠΈ ΠΊΠΎΠ»-Π²Π° ΡΡΠ°ΡΡΠ½ΠΈΠΊΠΎΠ² lst.append(k) lst_sort = sorted(lst, key=lambda x: x[1]) #Π‘ΠΎΡΡΠΈΡΠΎΠ²ΠΊΠ° ΠΏΠΎ ΠΊΠΎΠ»-Π²Ρ ΡΡΠ°ΡΡΠ½ΠΈΠΊΠΎΠ² print (lst_sort) lst1 = lst_sort[-10:] #10 ΡΠ°ΠΌΡΡ
ΠΏΠΎΠΏΡΠ»ΡΡΠ½ΡΡ
print(lst1)
top10groups = collections.Counter(g.id for m in members(group) for g in groups(m.id)).most_common(10). Try another connection pool (requests module) and group requests (more than one subscriber at a time β 25 at a time if you believe the answer below). - jfs