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

如何用while循环生成对话嵌套列表并按对话分组

解决方案

你的核心需求是按对话分组(以turn_index=0为新对话起点),再对每个对话生成相邻轮次的句子对。你的代码问题在于没处理对话分组逻辑,循环嵌套混乱,且字段提取有误。

下面是修正后的可运行代码:

# 假设data是已打开的文件对象
turns = [line.rstrip().split("\t") for line in data.readlines()]

dialogues = []
current_dialogue = []

for turn in turns:
    turn_idx, sentence, _ = turn  # 忽略metadata字段
    if int(turn_idx) == 0:
        # 遇到新对话,先处理完上一个对话(如果存在)
        if current_dialogue:
            pairs = [[current_dialogue[i], current_dialogue[i+1]] for i in range(len(current_dialogue)-1)]
            dialogues.append(pairs)
            current_dialogue = []
        current_dialogue.append(sentence)
    else:
        current_dialogue.append(sentence)

# 处理最后一个未完成的对话
if current_dialogue:
    pairs = [[current_dialogue[i], current_dialogue[i+1]] for i in range(len(current_dialogue)-1)]
    dialogues.append(pairs)

# 输出结果
for idx, res in enumerate(dialogues):
    print(f"对话{idx+1}结果: {res}")

关键逻辑说明

  1. 数据解析:用列表推导式读取所有行,按制表符\t拆分每个轮次的字段,提取需要的句子内容。
  2. 对话分组:
    • 用current_dialogue临时存储当前对话的所有句子,dialogues保存所有对话的最终结果。
    • 当遇到turn_index=0的行时,判定为新对话,先将上一个对话的句子生成相邻对并存入结果,再重置临时列表。
  3. 生成相邻句子对:对每个对话的句子列表,通过遍历索引生成[当前句, 下一句]的子列表。

测试示例数据

输入你提供的示例内容后,代码会输出:

对话1结果: [['hello', 'hi!']]
对话2结果: [['hi there', 'how are you?'], ['how are you?', 'very well'], ['very well', "I'm so busy today"]]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 09:50:25