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

I have a function. Is there any better way to modify my function according to the conditions?

4
  • What do you want your function to do? Can you share some sample inputs and outputs ? Commented Apr 29, 2019 at 8:54
  • 1
    Is the expected output ['cat 88.96%', 'rabbit 12.44%'] ? Commented Apr 29, 2019 at 8:56
  • @DeveshKumarSingh no,get the string I setting --> ['cat', 'rabbit'] Commented Apr 29, 2019 at 9:02
  • 1
    So if your input and output are same? What is the function doing? Commented Apr 29, 2019 at 9:03

4 Answers 4

1

If I understand you correctly, is this what you are looking for?

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

Sign up to request clarification or add additional context in comments.

Comments

1

You can use itertools.product to generate the pairs for comparison:

>>> product = itertools.product(cond, input_list)
>>> [p for (p, q) in product if p in q]
['cat', 'rabbit']

Comments

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)

Comments

0

This is one approach using regex and a list comprehension

Ex:

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)

Output:

['cat', 'rabbit']

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.