Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to make if inside for loop using lambda?

I have list_a and string_tmp like this

list_a = ['AA', 'BB', 'CC']
string_tmp = 'Hi AA How Are You'

I want to find out is there any of string_tmp items in the list_a, if it is, type = L1 else type = L2?

# for example
type = ''
for k in string_tmp.split():
    if k in list_a:
        type = 'L1'
if len(type) == 0:
    type = 'L2'

this is the real problem but in my project, len(list_a) = 200,000 and len(strgin_tmp) = 10,000, so I need that to be super fast

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

# this is the output of the example 
type = 'L1'

>Solution :

Converting the reference list and string tokens to sets should enhance performance. Something like this:

list_a = ['AA', 'BB', 'CC']
string_tmp = 'Hi AA How Are You'

def get_type(s, r): # s is the string, r is the reference list
    s = set(s.split())
    r = set(r)
    return 'L1' if any(map(lambda x: x in r, s)) else 'L2'

print(get_type(string_tmp, list_a))

Output:

L1
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading