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

Python:如何获取嵌套字符串列表中包含指定子串的所有字符串?

问题:在嵌套字符串列表中搜索子串并获取匹配的原字符串

我想在嵌套字符串列表L1里搜索子字符串列表L2,参考的帖子原本实现的是找到匹配的列表索引,但我的需求是获取所有包含L2中子串的L1原字符串。目前我的代码只能拿到匹配的L1列表索引,而且搜索第二个和第三个元素时会报错。

原代码

from bisect import bisect_left, bisect_right
from itertools import chain
    
L1=[["animal:cat","pet:dog","fruit:apple"],["fruit:orange","color:green","color:red","fruit:apple"]]
L2=["apple", "cat","red"]

M1 = [[i]*len(j) for i, j in enumerate(L1)]
M1 = list(chain(*M1))

L1flat = list(chain(*L1))

I = sorted(range(len(L1flat)), key=L1flat.__getitem__)
L1flat = sorted([L1flat[i].split(':')[1] for i in I])
print(L1flat)
M1 = [M1[i] for i in I]

for item in L2:
    s = bisect_left(L1flat, item)
    e = bisect_right(L1flat, item)    
    print(item, M1[s:e])
    #print(L1flat[s:e])
    sub = M1[s:e]
    for y in sub:
        print('%s found in %s' % (item, str(L1(y))))

修改尝试

发现报错后,我做了以下调整:

  • 通过枚举拆分后的L1元素创建M1:
    L1Splitted = [i[0].split(':')[1] for i in L1]
    M1 = [[i]*len(j) for i, j in enumerate(L1Splitted)]
    
  • 反转L1flat中的元素并拆分:
    L1flatReversed = []
    for j, x in enumerate(L1flat):
        L1flatReversed.append(reverseString(x, ':'))
    
  • 创建反转字符串拆分后的列表,基于它用bisect查找s和e:
    L1flatReversedSplit = [L1flatReversed[i].split(':')[0] for i in I]
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.02 02:33:26