我正在跟踪帖子Search a list of list of strings for a list of strings in python efficiently,并try 在字符串列表中搜索子字符串列表.上面的帖子查找与字符串列表匹配的字符串列表的索引.在我的代码中,我子串L1并将其展平以匹配L2字符串.如何获取以L2字符串为子字符串的所有L1字符串的列表?现在,我正在获取匹配每个L2字符串的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))))

编辑:我刚刚意识到我在搜索第二和第三项时遇到了错误.

三件事:

  1. 我通过枚举L1的拆分元素创建了M1

    L1Splited=[I[0].Split(‘:’)[1]用于L1中的I]

    M1=[[i]*len(J)for i,j in枚举(L1拆分)]

  2. 我反转了L1Flat中的元素并拆分了元素

    L1flatReversed = []

    对于枚举中的j,x(L1Flat)

     L1flatReversed.append(reverseString(x, ':'))
    
  3. 然后我将另一串颠倒的字符串拆分

    L1Flat ReversedSplit=[L1Flat Reversed[i].Split(‘:’)[0]for i in i]

现在我的S和e在L1平坦上一分为二

推荐答案

我会把L1映射到我们可以搜索的东西上,因为我们似乎知道在L1的值中可能会找到我们的搜索词.然后,只需将这组单词与我们的搜索条件相交即可

L1 = [
    ["animal:cat", "pet:dog", "fruit:apple"],
    ["fruit:orange", "color:green", "color:red", "fruit:apple"]
]
L2 = ["apple", "cat", "red"]

## ------------------
## Create a reshaping of "L1" based on where we know we can find
## strings to match
## ------------------
L1_lookup = [
    set(cell.split(":")[1] for cell in row)
    for row in L1
]
## ------------------

## ------------------
## match the set of words against the search words
## ------------------
results = [
    (L1[index], intersection)
    for index, value
    in enumerate(L1_lookup)
    if (intersection := value.intersection(L2))
]
## ------------------

for row, intersection in results:
    print(row, f"{intersection=}")

应该给你:

['animal:cat', 'pet:dog', 'fruit:apple'] intersection={'apple', 'cat'}
['fruit:orange', 'color:green', 'color:red', 'fruit:apple'] intersection={'red', 'apple'}

Python相关问答推荐

带有Postgres的Flask-Data在调用少量API后崩溃

我可以使用极点优化这个面向cpu的pandas代码吗?

使用Python C API重新启动Python解释器

如何匹配3D圆柱体的轴和半径?

将从Python接收的原始字节图像数据转换为C++ Qt QIcon以显示在QStandardProject中

避免循环的最佳方法

Pandas 除以一列中出现的每个值

如何计算列表列行之间的公共元素

将HLS纳入媒体包

rame中不兼容的d类型

在Python Attrs包中,如何在field_Transformer函数中添加字段?

Excel图表-使用openpyxl更改水平轴与Y轴相交的位置(Python)

Pandas - groupby字符串字段并按时间范围 Select

在Polars(Python库)中将二进制转换为具有非UTF-8字符的字符串变量

Pandas:将多级列名改为一级

使用密钥字典重新配置嵌套字典密钥名

合并帧,但不按合并键排序

PYTHON、VLC、RTSP.屏幕截图不起作用

polars:有效的方法来应用函数过滤列的字符串

pandas:在操作pandora之后将pandora列转换为int