[英]python: Searching strings in one list in another list, then appending an entire list entry to a new list
例:
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
但这没用。 我正在使用的实际列表要长得多,因此高效的代码确实可以帮助我。
谢谢!
尝试
s = set(L1)
new_list = [a for a in L2 if any(b in s for b in a)]
也许
s = set(L1)
new_list = [a for a in L2 if s.intersection([w.strip() for w in set(a.split(","))])]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.