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

如何使用Python基于列表指定关键元素拆分拼接对应数据?

你可以先按分隔符aaa将原始列表拆分为多个独立的处理块,再针对每个块单独处理,逻辑非常清晰,不需要嵌套循环。

实现代码

# 原始输入列表
raw_list = ['aaa', 'bbb', 'ccc', 'ABN', 'AMRO', 'Bank', 'N.V.', '\nYour', 'monthly', 'statement', 'is', 'available', 'under', 'Self', 'service', '>', '\nDownload', 'statements', 'or', 'u', 'receive', 'them', 'by', 'mail.', 'aaa', 'bbb', 'ccc', 'ddd', '/TRTP/SEPA', 'OVERBOEKING/IBAN/NL93RABO0127299726/BIC/RABONL2U/NAME/', '\nPointbar', 'B.V./REMI/INV', '121-10005/EREF/NONREF', 'aaa', 'bbb', 'ccc', 'Settlement', 'FX/MM', '\nTrans.', 'Ref.', '0035979579', 'Deal', 'Ticket', 'ID', '6225447']

# 第一步:按aaa分割为多个处理块,过滤掉空块
blocks = []
current_block = []
for item in raw_list:
    if item == 'aaa':
        if current_block:
            blocks.append(current_block)
            current_block = []
    else:
        current_block.append(item)
# 加入最后一个未收尾的块
if current_block:
    blocks.append(current_block)

result_segments = []
for block in blocks:
    # 找到当前块里ccc的索引位置
    ccc_idx = block.index('ccc')
    # 提取ccc之后的所有元素
    content_after_ccc = block[ccc_idx + 1:]
    # 检查ccc之后是否存在ddd
    if 'ddd' in content_after_ccc:
        ddd_idx = content_after_ccc.index('ddd')
        # 取ddd之后的元素作为有效内容
        valid_content = content_after_ccc[ddd_idx + 1:]
    else:
        valid_content = content_after_ccc
    # 拼接成字符串加入结果段
    result_segments.append(' '.join(valid_content))

# 用两个换行连接所有段落,得到最终结果
final_str = '\n\n'.join(result_segments)
print(final_str)

输出结果

执行代码后输出和预期完全一致:

ABN AMRO Bank N.V.
Your monthly statement is available under Self service >
Download statements or u receive them by mail.

/TRTP/SEPA OVERBOEKING/IBAN/NL93RABO0127299726/BIC/RABONL2U/NAME/
Pointbar B.V./REMI/INV 121-10005/EREF/NONREF

Settlement FX/MM
Trans. Ref. 0035979579 Deal Ticket ID 6225447

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 18:57:00