def myFunction(cond_list, input_list):
res = []
data = list(set(input_list)) # filter duplicate elements
for i in cond_list:
for j in data:
if i in j:
res.append(i)
return res
cond = ['cat', 'rabbit']
input_list = ['', 'cat 88.96%', '.', 'I have a dog', '', 'rabbit 12.44%', '', 'I like tiger']
result = myFunction(cond_list=cond, input_list=input_list)
print(result) # the input list have: ['cat', 'rabbit']
我有一个功能。有什么更好的方法可以根据情况修改我的功能?
答案 0 :(得分:1)
如果我对您的理解正确,这就是您要寻找的吗?
cond = ['cat', 'rabbit'] # filter duplicate elements
input_list = ['', 'cat 88.96%', '.', 'dog 40.12%', '', 'rabbit 12.44%', '', 'tiger 85.44%']
[i for i in cond for j in input_list if i in j]
['cat','rabbit']
答案 1 :(得分:1)
您可以使用itertools.product生成用于比较的对:
>>> product = itertools.product(cond, input_list)
>>> [p for (p, q) in product if p in q]
['cat', 'rabbit']
答案 2 :(得分:0)
cond = ['cat', 'rabbit'] # filter duplicate elements
input_list = ['', 'cat 88.96%', '.', 'dog 40.12%', '', 'rabbit 12.44%', '', 'tiger
85.44%']
matching = list(set([s for s in input_list if any(xs in s for xs in cond)]))
for i in matching:
print(i)
答案 3 :(得分:0)
这是使用正则表达式和列表理解的一种方法
例如:
import re
def myFunction(cond_list, input_list):
data = set(input_list) # filter repeat element
pattern = re.compile("|".join(data))
return [i for i in cond_list if pattern.search(i)]
cond = ['cat', 'rabbit'] # filter duplicate elements
input_list = ['', 'cat 88.96%', '.', 'dog 40.12%', '', 'rabbit 12.44%', '', 'tiger 85.44%']
result = myFunction(cond_list=cond, input_list=input_list)
print(result)
输出:
['cat', 'rabbit']