例:
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')]
Run Code Online (Sandbox Code Playgroud)
我试图在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
Run Code Online (Sandbox Code Playgroud)
但那没用.我使用的实际列表要长得多,所以一个高效的代码真的可以帮助我.
谢谢!
尝试
s = set(L1)
new_list = [a for a in L2 if any(b in s for b in a)]
Run Code Online (Sandbox Code Playgroud)