user10737394
user10737394

Reputation: 107

Match partially in the list

list1 = ['  I am Sam', 'It is 1,2,3  ', ' It is hot right now' ]

match1 = 'I am'
match2 = 'is 1,2'
match3 = 'hot right now'

Return true if all of match1, match2, match3 are present and match in list1. There are white strings in list1

def check(the_list, *match):
    return all(a in the_list for a in match)
if check(list1, match1, match2, match3):
    return True

I can return if it's exact match, but what's best way to match in the list even though match is partial?

Upvotes: 0

Views: 53

Answers (2)

Valentino
Valentino

Reputation: 7361

a in a_string returns True if a is a substring of a_string. So you just need to fix the list comprehension, which needs to be a bit more complex.

list1 = ['  I am Sam', 'It is 1,2,3  ', ' It is hot right now' ]

match1 = 'I am'
match2 = 'is 1,2'
match3 = 'hot right now'

def check(the_list, *match):
    return all(any(a in listel for listel in the_list) for a in match)

print(check(list1, match1, match2, match3))

It prints True if all matches are substring of at least one of the strings in the_list. Order does not matter and it does not require a one to one correspondence. I mean that if all the matches are substring of the same element, it still returns True. For example, if you use match1 = 'I am', match2 = 'am', match3 = ' I' it still returns True.

Upvotes: 1

Edword
Edword

Reputation: 78

I'm not 100% sure this is what you want to do, but I reckon it is:

list1 = ['  I am Sam', 'It is 1,2,3  ', ' It is hot right now' ]

match1 = 'I am'
match2 = 'is 1,2'
match3 = 'hot right now'


def check(the_list, *match):
    return all(any(w in p for p in the_list) for w in match)))

print(check(list1, match1, match2, match3))

You want partial matches, so strings do not need to be equal, but match must be a substring of your list.

Upvotes: 1

Related Questions