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

如何在Python中将列表中文本与紧随其后的数字拼接

解决Python列表中文本与后续数字元素拼接的问题

需求说明

遍历输入列表,将每个文本元素与紧随其后的数字元素拼接为新字符串,生成目标列表。

输入示例

a = ["hello", "hello", "1", "hello", "2"]
b = ["hello", "hello", "1"]
c = ["hello", "1"]

期望输出

a = ["hello", "hello 1", "hello 2"]
b = ["hello", "hello 1"]
c = ["hello 1"]

解决方案

这里提供两种实用实现方式:

方法一:索引遍历法(直观易懂)

def merge_text_and_num(lst):
    result = []
    i = 0
    n = len(lst)
    while i < n:
        # 处理非数字元素,检查下一个是否为数字
        if not lst[i].isdigit():
            if i + 1 < n and lst[i+1].isdigit():
                result.append(f"{lst[i]} {lst[i+1]}")
                i += 2  # 跳过已拼接的数字元素
            else:
                result.append(lst[i])
                i += 1
        else:
            # 单独的数字元素直接加入结果(可按需调整逻辑)
            result.append(lst[i])
            i += 1
    return result

方法二:迭代器法(灵活处理元素)

import collections

def merge_text_and_num(lst):
    result = []
    it = iter(lst)
    for item in it:
        if not item.isdigit():
            try:
                next_item = next(it)
                if next_item.isdigit():
                    result.append(f"{item} {next_item}")
                else:
                    result.append(item)
                    # 将非数字元素放回迭代器,留到下一轮处理
                    it = collections.chain([next_item], it)
            except StopIteration:
                # 已到列表末尾,直接加入当前元素
                result.append(item)
        else:
            result.append(item)
    return result

测试验证

a = ["hello", "hello", "1", "hello", "2"]
b = ["hello", "hello", "1"]
c = ["hello", "1"]

print(merge_text_and_num(a))  # 输出: ['hello', 'hello 1', 'hello 2']
print(merge_text_and_num(b))  # 输出: ['hello', 'hello 1']
print(merge_text_and_num(c))  # 输出: ['hello 1']

说明

  • 两种方法默认非数字字符串为文本元素,如果你的文本有特殊判断规则(比如必须是特定字符串),可修改isdigit()的判断逻辑。
  • 索引遍历法代码简洁,适合输入列表结构规整的场景;迭代器法更灵活,能处理元素顺序多变的情况。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 08:45:32