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

Python中如何依据索引列表对数据列表进行排序?

根据完赛编号排序参与者列表

我有两个作业文件:

  • 第一个是带前置编号的参与者列表,示例内容:
    1. John
    2. Kate
    3. Jimmy
  • 第二个是对应完赛编号的列表,示例内容:
    3
    1
    2
    

需要生成按完赛顺序排列的参与者列表,结果应该是:

  1. Jimmy
  2. John
  3. Kate

现在我没法正确获取结果索引,也不知道怎么把它和初始参与者列表关联起来,现有代码如下:

with open("participants.txt") as f:
    participants = []
    for line in f:
        participants.append(line.strip().split(". "))
    for i in range(len(participants)):   
        try:
            participants[i][0] = int(participants[i][0])
        except:
            continue
with open("participantresults.txt") as d:
    participantresults = []
    for line in d:
        participantresults.append(line.strip("\n"))
    # 原代码变量名写错,修正为participantresults
    for i in range(len(participantresults)):   
        participantresults[i] = int(participantresults[i])

resultindex = []
for n in participantresults:
    resultindex.append(participantresults.index(n)) # 这里逻辑错误

result = []
for n in range(len(resultindex)):
  ..... 

with open("result.txt", "w") as f:
   #write the list here later.

修正方案

核心思路是把参与者的编号和名字对应成字典,直接通过完赛编号快速查找对应参与者,不用绕索引:

  1. 读取参与者文件并构建字典:将每一行的编号转成整数作为键,名字作为值,查找更高效;
  2. 读取完赛编号并转成整数列表:确保每个元素都是整数类型;
  3. 按完赛顺序生成结果列表:遍历完赛编号列表,从字典中取出对应的名字;
  4. 写入结果文件:按编号格式写入最终排序后的列表。

完整修正代码

# 读取参与者文件,构建{编号: 名字}的字典
participant_dict = {}
with open("participants.txt") as f:
    for line in f:
        # 只做一次分割,避免名字里有". "的情况
        parts = line.strip().split(". ", 1)
        if len(parts) == 2:
            try:
                num = int(parts[0])
                name = parts[1]
                participant_dict[num] = name
            except ValueError:
                # 跳过编号无效的行
                continue

# 读取完赛编号列表,只保留有效的数字行
with open("participantresults.txt") as d:
    finish_order = [int(line.strip()) for line in d if line.strip().isdigit()]

# 按完赛顺序生成结果列表
result = []
for num in finish_order:
    if num in participant_dict:
        result.append(participant_dict[num])
    else:
        # 处理不存在的编号,可选:跳过或标记
        result.append(f"未知参与者(编号{num})")

# 写入结果文件,自动生成前置编号
with open("result.txt", "w") as f:
    for idx, name in enumerate(result, start=1):
        f.write(f"{idx}. {name}\n")

代码说明

  • 用split(". ", 1)避免名字包含". "时的分割错误;
  • 字典存储参与者,通过编号直接查询名字,比列表索引更直观高效;
  • 加入异常处理,跳过无效的编号行;
  • 用enumerate(start=1)自动生成结果的前置编号,符合输出格式要求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.08 02:28:16