如何修改字典遍历代码:将关注列表转换为粉丝列表
问题:如何从用户关注列表转换为粉丝列表?
你当前使用的用户字典如下:
members = { 1: {"name": "Farly Waller", "country": "Russia", "following": [11, 18, 17, 20]}, 2: {"name": "Jania Hardistry", "country": "Indonesia", "following": [3, 8, 15, 20]}, 3: {"name": "Yale Shortan", "country": "Brazil", "following": [2, 4, 8]}, 4: {"name": "Redford Melloi", "country": "Philippines", "following": [1, 3, 13, 14]}, 5: {"name": "Lisbeth Cello", "country": "Pakistan", "following": [4, 7, 10]}, 6: {"name": "Andrew Flaonier", "country": "Pakistan", "following": []}, 7: {"name": "Pris Pilmore", "country": "Japan", "following": [5, 6, 9, 1, 15, 16]}, 8: {"name": "Starla Buffey", "country": "Colombia", "following": [10, 2, 3]}, 9: {"name": "Clark Goymer", "country": "Thailand", "following": [7, 11]}, 10: {"name": "Gayle Testin", "country": "Brazil", "following": [8, 5, 15, 19, 13]}, 11: {"name": "Serena Brombell", "country": "China", "following": [1, 17, 18]}, 12: {"name": "Wendy Toke", "country": "Peru", "following": []}, 13: {"name": "Clarice Shelmardine", "country": "Portugal", "following": [10, 1, 14, 15, 16, 19]}, 14: {"name": "Julie Corradeschi", "country": "Peru", "following": [13, 1, 2, 4]}, 15: {"name": "Constantin Sebire", "country": "China", "following": [3, 10, 13, 16, 18]}, 16: {"name": "Annadiane Mum", "country": "Japan", "following": [7, 13, 6, 18]}, 17: {"name": "Lovell Lubbock", "country": "China", "following": [1, 11, 20]}, 18: {"name": "Gwynne Toplis", "country": "China", "following": [1, 11, 16, 17]}, 19: {"name": "Pammy Urey", "country": "Yemen", "following": [10, 6, 13, 20]}, 20: {"name": "Celestina Phillipps", "country": "Canada", "following": [3, 17]}, }
你写的代码如下:
followers = {} for user_id in members: followers[user_id]=[] for user1 in members[user_id]["following"]: if user1 in members[user_id]["following"]: followers[user_id].append(user1) print(followers)
这段代码只是把每个用户的关注列表直接复制到followers字典中,但你实际需要的是每个用户的粉丝列表——也就是哪些用户关注了当前用户。比如用户5的粉丝列表应为[7, 10],用户1的粉丝列表应为[4, 7, 11, 13, 14, 17, 18]。
解决方案
修改代码的核心逻辑是:遍历每个用户的关注列表,将当前用户ID添加到他所关注的用户的粉丝列表中。具体代码如下:
# 初始化所有用户的粉丝列表为空 followers = {user_id: [] for user_id in members} # 遍历每个用户及其数据 for current_user_id, user_info in members.items(): # 遍历当前用户关注的每一个用户 for followed_id in user_info["following"]: # 将当前用户添加到被关注用户的粉丝列表里 followers[followed_id].append(current_user_id) print(followers)
逻辑说明:
- 初始化粉丝字典:用字典推导式快速创建一个包含所有用户ID的字典,每个ID对应一个空列表,确保没有用户被遗漏。
- 遍历用户与关注列表:外层循环逐个取出用户ID和对应的信息,内层循环遍历该用户关注的所有ID。
- 填充粉丝列表:每遍历到一个被关注的ID,就把当前用户ID添加到这个被关注ID的粉丝列表中——这就相当于记录了“当前用户关注了这个ID,所以当前用户是这个ID的粉丝”。
运行这段代码后,就能得到你需要的粉丝列表:
- 用户5的粉丝列表为
[7, 10](用户7和10都关注了5) - 用户1的粉丝列表为
[4, 7, 11, 13, 14, 17, 18],完全符合预期。
内容的提问来源于stack exchange,提问作者Emma__BB
相关产品推荐
相关产品推荐

