You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

获取关注者子集中各账号的被关注频次

你可以用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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.02 08:15:31