开发者

python: Searching strings in one list in another list, then appending an entire list entry to a new list

开发者 https://www.devze.com 2023-02-06 23:55 出处:网络
Example: L1=[\'cat\', \'dog\', \'fish\', \'bird\', \'rabbit\', \'horse\'] L2=[(\'cat\', \'a\', \'b\', \'c\'), (\'cat\', \'c\', \'d\', \'e\'), (\'cat\', \'e\', \'f\', \'g\'), (\'fish\', \'x\', \'y\',

Example:

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')]

I am trying to search the strings in L1 in L2, so that if the string in L1 is present in any part of L2, the whole entry from L2 "('cat, a, b, c')" is appended to a new list. I also thought that maybe removing the entries that do not have any part of a string from L1 would work. I tried:

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

    return 开发者_高级运维common

but that didnt work. The actual list I am using is much longer, so an efficient code would really help me out.

Thanks!


Try

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


Maybe

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

精彩评论

暂无评论...
验证码 换一张
取 消