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

Python if语句判断为真却不执行 排行榜排名计算问题排查

问题修复方案

错误原因

核心错误是混淆了Python的运算符:

  • 你代码中使用的&是位运算符,优先级远高于==、>=这类比较运算符,因此iteration == 0 & score >= rank不会按照你预期的「iteration等于0 且 分数大于等于当前排名分」执行,实际会被解析为iteration == (0 & score) and (0 & score) >= rank。
  • 计算玩家分数120时,0 & 120结果为0,因此上述条件变为iteration == 0 and 0 >=100,结果为False,反而下一个分支iteration == 0 & score < rank的解析结果是iteration ==0 and 0 <100,结果为True,因此出现了120被误判小于100的假象。
    额外还有一个潜在问题:player.index(score)在玩家列表存在重复分数时会永远返回第一个匹配项的索引,导致排名赋值错误。

修复方法

快速修复(保留原有代码逻辑)

只需要把两个iteration==0判断中的&替换为逻辑与运算符and即可:

ranked = [100, 100, 50, 40, 40, 20, 10]
player = [5, 25, 50, 120]

def climbingLeaderboard(ranked, player):
    ranks = []
    for score in player:
        iteration = 0
        temp = 0
        ranks.append(0)
        for rank in ranked:
            if rank == temp:
                continue
            # 把&替换为and
            elif iteration == 0 and score >= rank:
                ranks[player.index(score)] += 1
            # 把&替换为and
            elif iteration == 0 and score < rank:
                ranks[player.index(score)] += 2
            elif score < rank:
                ranks[player.index(score)] += 1
            elif score == rank:
                break
            iteration += 1
            temp = rank
    print(ranks)

climbingLeaderboard(ranked, player)

优化版方案(性能更高,无重复分数bug)

提前对排行榜分数去重,减少循环次数,同时直接按遍历顺序赋值排名,避免使用index方法:

ranked = [100, 100, 50, 40, 40, 20, 10]
player = [5, 25, 50, 120]

def climbingLeaderboard(ranked, player):
    # 先对排行榜去重并保持降序
    unique_ranked = sorted(set(ranked), reverse=True)
    ranks = []
    for score in player:
        current_rank = 1
        for r in unique_ranked:
            if score >= r:
                break
            current_rank += 1
        ranks.append(current_rank)
    print(ranks)

climbingLeaderboard(ranked, player)

两种方案运行后都会输出预期结果[6, 4, 2, 1]。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 11:54:00