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

如何合并数组中拆分的单个字符元素以生成完整标签?

实现方案

这里提供两种常见场景的实现方式,基于Python完成字符数组的拼接格式化:

1. 处理普通Python列表数组

如果你的数组是普通的Python列表结构,可通过列表推导式快速完成拼接:

original_array = [
    ['1', '.', ' ', 'I', 'd', 'e', 'n', 't', 'i', 'f', 'y', 'i', 'n', 'g', ',', ' ', 'A', 's', 's', 'e', 's', 's', 'i', 'n', 'g', ' ', 'a', 'n', 'd', ' ', 'I', 'm', 'p', 'r', 'o', 'v', 'i', 'n', 'g', ' ', 'C', 'a', 'r', 'e', '', ''],
    ['9', '.', ' ', 'N', 'o', 'n', '-', 'P', 'h', 'a', 'r', 'm', 'a', 'c', 'o', 'l', 'o', 'g', 'i', 'c', 'a', 'l', ' ', 'I', 'n', 't', 'e', 'r', 'v', 'e', 'n', 't', 'i', 'o', 'n', 's', '', '', '', '', '']
]

# 遍历每个子数组,过滤空字符串后拼接
formatted_array = [''.join([char for char in sub_arr if char != '']) for sub_arr in original_array]
print(formatted_array)

输出结果:

['1. Identifying, Assessing and Improving Care', '9. Non-Pharmacological Interventions']

2. 处理NumPy数组

如果你的数组是NumPy格式,先转换为Python列表再处理即可:

import numpy as np

original_np_array = np.array([
    ['1', '.', ' ', 'I', 'd', 'e', 'n', 't', 'i', 'f', 'y', 'i', 'n', 'g', ',', ' ', 'A', 's', 's', 'e', 's', 's', 'i', 'n', 'g', ' ', 'a', 'n', 'd', ' ', 'I', 'm', 'p', 'r', 'o', 'v', 'i', 'n', 'g', ' ', 'C', 'a', 'r', 'e', '', ''],
    ['9', '.', ' ', 'N', 'o', 'n', '-', 'P', 'h', 'a', 'r', 'm', 'a', 'c', 'o', 'l', 'o', 'g', 'i', 'c', 'a', 'l', ' ', 'I', 'n', 't', 'e', 'r', 'v', 'e', 'n', 't', 'i', 'o', 'n', 's', '', '', '', '', '']
], dtype=str)

# 遍历每一行,过滤空字符后拼接
formatted_np_array = np.array([''.join([c for c in row if c != '']) for row in original_np_array])
print(formatted_np_array)

输出结果:

array(['1. Identifying, Assessing and Improving Care',
       '9. Non-Pharmacological Interventions'], dtype='<U44')

核心逻辑:遍历每一组拆分后的字符序列,过滤掉空字符串,将剩余字符拼接成完整字符串,最终组成新的目标数组。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 15:50:49