python - 有效地在字符串列表中搜索 python 中的字符串列表

标签 python list

我有一个字符串列表和一个字符串列表。例如:

L1=[["cat","dog","apple"],["orange","green","red"]]
L2=["cat","red"]

如果 L1[i] 包含 L2 中的任何项目,我需要放置对(用于在图中创建边) 比如,在我的示例中,我需要对 ("cat","dog"),("cat,apple"),("red,orange"),("red","green")

我应该使用什么方法来使其最有效。 (我的列表 L1 很大)

最佳答案

假设您的 L1 子列表中可能有多个“控制”项。

我会使用 set() 来做到这一点和 itertools.product() :

from itertools import product

def generate_edges(iterable, control):
    edges = []
    control_set = set(control)
    for e in iterable:
        e_set = set(e)
        common = e_set & control_set
        to_pair = e_set - common
        edges.extend(product(to_pair, common))
    return edges

例子:

>>> L1 = [["cat","dog","apple"],
...       ["orange","green","red"],
...       ["hand","cat","red"]]
>>> L2 = ["cat","red"]
>>> generate_edges(L1, L2)
[('apple', 'cat'),
 ('dog', 'cat'),
 ('orange', 'red'),
 ('green', 'red'),
 ('hand', 'red'),
 ('hand', 'cat')]

关于python - 有效地在字符串列表中搜索 python 中的字符串列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9316970/

相关文章:

python - Pandas:为什么 DataFrame.apply(f, axis=1) 在 DataFrame 为空时调用 f?

python - 是否可以将 Django 的 SafeExceptionReporterFilter 与 AdminEmailHandler 以外的其他东西一起使用?

Python:从文本文件导入列表并根据多列进行排序/平均

python - 操作二维列表区域的更短方法

Python 无法引用调用类中的列表

c++ - 用于 C++ 运算符重载的 Python 绑定(bind)

Python3 - 将每个字符附加到一个字符串(制作一行)

python - 获取最近附加项目的索引

python - 美丽汤无法使用 Div 从网站找到数据

python - 在某些条件下从列表中提取数据