python: 在一个列表中查找另一个列表的字符串并将整个列表条目添加到新列表

1 投票
2 回答
575 浏览
提问于 2025-04-16 10:32

示例:

L1=['cat', 'dog', 'fish', 'bird', 'rabbit', 'horse']

L2=[('cat', 'a', 'b', 'c'), ('cat', 'c', 'd', 'e'), ('cat', 'e', 'f', 'g'), ('fish', 'x', 'y', 'z'), ('dog', 'w', 'x', 'y'), ('dog', 'z', 'y', 'x'), ('horse', '1', '2', '3'), ('monkey', 'a', 'b', 'c'), ('kitten', 'h', 'i', 'j'), ('bird', '4', '5', '6')]

我想在L2中查找L1里的字符串,也就是说,如果L1中的字符串出现在L2的任何部分,那么就把L2中的整条记录 "('cat, a, b, c')" 加到一个新的列表里。我还想过,也许把那些没有L1中任何字符串的记录删掉也可以。

我试过:

def searcher(L1, L2):
    common = []
    for x in L1:
        if re.search(x, L2):
            common.append(L2)

    return common

但是没有成功。实际上我用的列表要长得多,所以写一个高效的代码对我来说真的很有帮助。

谢谢!

2 个回答

0

也许吧

s = set(L1)
new_list = [a for a in L2 if s.intersection([w.strip() for w in set(a.split(","))])]
5

试试看

s = set(L1)
new_list = [a for a in L2 if any(b in s for b in a)]

撰写回答