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

Python如何合并列表中from关键字后围绕.的相邻元素得到预期输出

问题修复方案

错误原因

原有代码遍历列表时,只有遇到.才会执行拼接逻辑,而.前后的ak和person会正常走else分支被添加到结果列表,最终就会出现多余的ak、person元素,和预期不符。

正确实现代码

直接定位from关键字的位置,保留from及之前的元素,将from之后的所有元素拼接为一个字符串添加即可,完全匹配需求:

a = ['select', '*', 'from', 'ak','.','person']
from_idx = a.index('from')
result = a[:from_idx + 1]
# 拼接from之后的所有元素
result.append(''.join(a[from_idx + 1:]))

运行后result的值就是预期的['select', '*', 'from', 'ak.person']。

如果场景需要适配多段.拼接的情况,也可以用遍历跳过的方案:

a = ['select', '*', 'from', 'ak','.','person']
res = []
skip_next = False
for idx, item in enumerate(a):
    if skip_next:
        skip_next = False
        continue
    if item == '.':
        # 弹出前一个元素,拼接当前和后一个元素
        pre = res.pop()
        res.append(f"{pre}{item}{a[idx+1]}")
        skip_next = True
    else:
        res.append(item)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 19:06:03