获取关注者子集中各账号的被关注频次
你可以用Python标准库的collections.Counter快速统计账号被关注次数,再按要求排序输出,具体修改如下:
修改后的完整代码片段
from collections import Counter # 原有的抓取逻辑保持不变 while count < int(numOfIDs): print(twitterUsernameArray[count] + " follows these accounts:") response = client.get_users_following(id=twitterIDArray[count], max_results=50, user_fields=['username']) for user in response.data: followerArray.append(user.username) count += 1 # 统计每个账号的被关注次数 follow_count = Counter(followerArray) # 按被关注次数降序排序,次数相同则按账号名升序排列 sorted_follows = sorted(follow_count.items(), key=lambda x: (-x[1], x[0])) # 按指定格式输出,处理单复数 for account, times in sorted_follows: print(f"{account} followed by {times} account{'s' if times != 1 else ''}")
关键逻辑说明
Counter(followerArray)会自动遍历列表,统计每个账号的出现次数,返回一个键为账号名、值为次数的字典结构。- 排序时用
lambda x: (-x[1], x[0])实现:先按次数降序(负号反转默认升序规则),次数相同的账号再按名称升序排列,和你给出的示例输出逻辑完全匹配。 - 输出时通过三元表达式
{'s' if times !=1 else ''}自动处理单复数,次数为1时显示account,大于1时显示accounts。
内容的提问来源于stack exchange,提问作者PackaLacken
相关产品推荐
相关产品推荐

