samedi 31 octobre 2020

Python matching partial strings in list elements between two lists

In my code I am trying to match the item from 'match' to the the strings in the 'data' list.

I want the code to look at the first word in 'match' list and if it matches with a string in the data 'list' then that will be added to another list. A second check I want to do is if the first 2 words in 'match' list match with the strings in data.

Currently my output is giving me only one instance of water12 - whereas both shoud have been picked up.

Please could someone let me know where I might be going wrong?


match =['f helo','happy hellp','floral', 'alpha','12133','water12 puppies']
data=['f we are', 'hello there', 'alpha beta','happy today is the case','112133 is it', 'floral is my fave', 'water12 if healthy','water12 puppies are here and exist']

lst=[]
for i in match:
    for j in data:
        if i.split()[0] in j:
            lst.append(j)
            data.remove(j)
            break
        if len(i) > 1:
            k= ' '.join(i.split()[:2])
            if k in j:
                lst.append(j) 
                data.remove(j)
                break
                
    else:
        lst.append(i + ' - not found')

print(lst)

Desired output:

output= [ 'f we are', 'alpha beta','happy today is the case','112133 is it', 'floral is my fave', 'water12 if healthy','water12 puppies are here and exist']

Aucun commentaire:

Enregistrer un commentaire