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

如何按规则拼接Python字符串列表 合并同属的分散描述条目

列表拼接实现方案

原代码问题说明

  • 未做分组逻辑,每个非name:开头的元素都会和下一个元素拼接,导致内容重复输出
  • 存在变量拼写错误:linha应为line
  • 遍历到最后一个元素时访问index+1会触发列表越界
  • 不符合「两个name:条目之间的所有内容合并为一条」的规则

正确实现代码

该方案时间复杂度为O(n),仅遍历一次列表,适配大体积列表场景:

def merge_name_list(origin_ls):
    result = []
    temp_parts = []
    for item in origin_ls:
        if item.startswith('name:'):
            # 遇到新的name条目,先合并上一组非name内容
            if temp_parts:
                result.append(''.join(temp_parts))
                temp_parts = []
            result.append(item)
        else:
            temp_parts.append(item)
    # 补充最后一组未合并的内容
    if temp_parts:
        result.append(''.join(temp_parts))
    return result

# 测试示例
ls = ['name: John', 'John has ', '4 yellow ', 'cars.', 'name: Angelina', 'Angelina has ', '5 yellow', 'cars.']
print(merge_name_list(ls))
# 输出:['name: John', 'John has 4 yellow cars.', 'name: Angelina', 'Angelina has 5 yellow cars.']

读文件场景适配版本

result = []
temp_parts = []
with open('names.txt', 'r', encoding='utf-8') as f:
    # 逐行读取并去除换行符
    for line in f:
        line = line.rstrip('\n')
        if line.startswith('name:'):
            if temp_parts:
                result.append(''.join(temp_parts))
                temp_parts = []
            result.append(line)
        else:
            temp_parts.append(line)
    # 处理最后一组内容
    if temp_parts:
        result.append(''.join(temp_parts))

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 07:27:05