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

如何使用for循环实现sort_by_chips函数完成玩家列表排序

sort_by_chips函数实现方案

核心规则与约束

  • 入参为嵌套结构的玩家列表,每个玩家子项的索引1存储参赛场次,索引5存储筹码余额
  • 排序优先级:
    • 第一优先级:筹码余额降序(数值越大越靠前)
    • 第二优先级:筹码相等时,参赛场次升序(数值越小越靠前)
  • 禁止修改传入的原列表,禁止使用任何内置排序函数/标准库排序能力、列表排序相关方法
  • 返回值为符合排序规则的新列表副本

实现思路

采用选择排序核心逻辑,全程不修改原列表:

  1. 初始化和原列表等长的标记数组,记录对应索引的玩家是否已经被加入结果列表,避免重复选取
  2. 循环n次(n为玩家总数),每次遍历所有未被标记的玩家,选出当前优先级最高的玩家
  3. 把选出的玩家追加到结果列表,同时标记该玩家索引为已选取
  4. 循环结束后返回结果列表,整个过程仅读取原列表内容,不会对原列表做任何修改

完整实现代码

def sort_by_chips(player_list):
    n = len(player_list)
    # 标记数组:记录对应索引玩家是否已加入结果,初始全为未选取状态
    selected = [False] * n
    sorted_result = []

    # 共需选取n个玩家,循环n次
    for _ in range(n):
        best_idx = -1
        for i in range(n):
            # 跳过已经选过的玩家
            if selected[i]:
                continue
            # 首次遍历到未选取玩家时,暂存为当前最优项
            if best_idx == -1:
                best_idx = i
                continue
            current_player = player_list[i]
            best_player = player_list[best_idx]
            # 当前玩家筹码更高,直接替换为最优项
            if current_player[5] > best_player[5]:
                best_idx = i
            # 筹码相等时,参赛场次更低的替换为最优项
            elif current_player[5] == best_player[5] and current_player[1] < best_player[1]:
                best_idx = i
        # 将本轮选出的最优玩家加入结果,标记为已选取
        sorted_result.append(player_list[best_idx])
        selected[best_idx] = True
    
    return sorted_result

效果验证

用题目给出的示例输入调用函数:

player_list = [['Bruce Wayne', 5, 5, 0, 0, 100, 15], ['Jessica Jones', 12, 0, 6, 6, 10, 6], ['Johnny Rose', 6, 2, 0, 4, 20, 10], ['Gina Linetti', 7, 4, 0, 3, 300, 15], ['Buster Bluth', 3, 0, 2, 1, 50, 1]]
print(sort_by_chips(player_list))

输出结果符合排序规则:

[
    ['Gina Linetti', 7, 4, 0, 3, 300, 15],
    ['Bruce Wayne', 5, 5, 0, 0, 100, 15],
    ['Buster Bluth', 3, 0, 2, 1, 50, 1],
    ['Johnny Rose', 6, 2, 0, 4, 20, 10],
    ['Jessica Jones', 12, 0, 6, 6, 10, 6]
]

注:题目给出的期望输出示例存在多余括号的笔误,上述输出为符合规则的正确结果。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.29 19:12:43