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

Python好友推荐循环逻辑出错,请求排查与正确实现方案

好友推荐逻辑错误排查与正确实现

需求说明

假设用户A与用户B是好友,用户B与用户C是好友。若用户C与用户A不是好友,则将用户C推荐给用户A。最终需创建按用户ID分组的推荐字典suggestions:

  • 键:用户ID
  • 值:待推荐好友ID列表,无推荐则为空列表

现有数据与错误代码

好友关系字典

friends = {1: [11, 17, 18], 2: [3, 8], 3: [2, 4, 8], 4: [3, 14], 5: [7, 10], 6: [], 7: [5, 9, 16], 8: [2, 3, 10], 9: [7], 10: [5, 8, 13, 15, 19], 11: [1, 17, 18], 12: [], 13: [10, 14, 15, 16, 19], 14: [4, 13], 15: [10, 13], 16: [7, 13, 18], 17: [1, 11, 20], 18: [1, 11, 16], 19: [10, 13], 20: [17]}

错误的循环逻辑

suggestions = {}
for user1 in friends:
    suggestions[user1] = []
    for user2 in friends: 
        for user3 in friends:
            if user1 in friends[user2] and user2 in friends[user3] and user3 not in friends[user1]:
                suggestions[user1].append(user3) 
                
print(suggestions)

错误输出示例

{1: [1, 1, 20, 1, 16], 2: [2, 4, 2, 10], 3: [3, 3, 14, 3, 10], 4: [2, 4, 8, 4, 13], 5: [5, 9, 16, 5, 8, 13, 15, 19], 6: [], 7: [7, 10, 7, 7, 13, 18], 8: [8, 4, 8, 5, 8, 13, 15, 19], 9: [5, 9, 16], 10: [7, 10, 2, 3, 10, 10, 14, 16, 10, 10], 11: [11, 11, 20, 11, 16], 12: [], 13: [5, 8, 13, 4, 13, 13, 7, 13, 18, 13], 14: [3, 14, 10, 14, 15, 16, 19], 15: [5, 8, 15, 19, 14, 15, 16, 19], 16: [5, 9, 16, 10, 14, 15, 16, 19, 1, 11, 16], 17: [17, 18, 17, 18, 17], 18: [17, 18, 17, 18, 7, 13, 18], 19: [5, 8, 15, 19, 14, 15, 16, 19], 20: [1, 11, 20]}

错误原因分析

  1. 遍历范围错误:代码遍历了所有用户作为user2和user3,而非仅遍历user1的好友作为user2,再遍历user2的好友作为user3。这会引入大量无关用户,甚至触发自我推荐的情况。
  2. 未排除自我推荐:没有判断user3是否等于user1,导致用户自己被加入推荐列表。
  3. 重复推荐未处理:同一个推荐好友可能通过多个中间好友被多次添加,导致列表中出现重复项。

正确实现代码

friends = {1: [11, 17, 18], 2: [3, 8], 3: [2, 4, 8], 4: [3, 14], 5: [7, 10], 6: [], 7: [5, 9, 16], 8: [2, 3, 10], 9: [7], 10: [5, 8, 13, 15, 19], 11: [1, 17, 18], 12: [], 13: [10, 14, 15, 16, 19], 14: [4, 13], 15: [10, 13], 16: [7, 13, 18], 17: [1, 11, 20], 18: [1, 11, 16], 19: [10, 13], 20: [17]}

suggestions = {}
for user1 in friends:
    # 用集合自动去重
    recommended = set()
    # 仅遍历user1的好友作为中间好友user2
    for user2 in friends[user1]:
        # 遍历user2的好友作为候选推荐user3
        for user3 in friends[user2]:
            # 排除自己、已有好友,符合条件则加入推荐集合
            if user3 != user1 and user3 not in friends[user1]:
                recommended.add(user3)
    # 转成排序后的列表(可选,若不需要排序可直接转list(recommended))
    suggestions[user1] = sorted(list(recommended))

print(suggestions)

代码解释

  1. 范围限定:只遍历user1的好友作为user2,再遍历user2的好友作为user3,符合需求中的“好友的好友”逻辑,避免无关数据。
  2. 去重处理:使用集合recommended存储推荐好友,自动避免重复项。
  3. 排除自我与已有好友:通过user3 != user1排除自我推荐,user3 not in friends[user1]确保推荐的不是已有的好友。
  4. 结果整理:将集合转为排序后的列表,保证输出结果整洁有序(若不需要排序可省略sorted)。

内容的提问来源于stack exchange,提问作者Emma__BB

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 06:40:35