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

Python如何对比列表与矩阵元素、去除匹配单词内部空格

解决代码及思路

核心思路

需求本质是对l2的第i行所有字符串,找到其中和l1[i]字符顺序完全一致、仅中间插入了空格的子串,将该子串内的所有空格删除,其余位置空格保留。我们可以用正则匹配快速实现:将目标词的每个字符之间插入\s*(匹配任意数量空格)生成匹配模式,直接将匹配到的内容替换为原目标词即可。

如果需要实现类似Java equalsIgnoreCase的大小写不敏感匹配,在正则编译时增加re.IGNORECASE参数即可。

完整实现代码

import re

l1=['soheila','mahin','rose','pari']
l2=[['so he ila ha','soh e i la h a','so h eil a ha'],
    ['ma h in','m ah in','mahi n'],
    ['r os es', 'ro se s','ros e s'],
    ['pa ri sa','pari s a','p ar i sa']]

output = []
for target, row in zip(l1, l2):
    # 生成匹配模式:目标词每个字符之间允许任意数量空格
    pattern = re.compile(r'\s*'.join(target))
    # 如需大小写不敏感,替换为下行代码
    # pattern = re.compile(r'\s*'.join(target), re.IGNORECASE)
    processed_row = [pattern.sub(target, s) for s in row]
    output.append(processed_row)

print(output)

输出验证

运行上述代码得到的输出和期望结果完全一致:

[['soheila ha', 'soheila h a', 'soheila ha'], 
['mahin', 'mahin', 'mahin'], 
['roses', 'rose s', 'rose s'], 
['pari sa', 'pari s a', 'pari sa']]

原有代码问题说明

你之前的代码逻辑是先把所有空格删除,无法做到仅删除匹配词内部的空格,同时列表判断i for i in l3[count_i] and new_data[count_i]的写法不符合Python语法规则,会导致逻辑错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 12:48:03