Inherited Geek
Inherited Geek

Reputation: 2393

Matching String in a List of Strings

I basically want to create a new list 'T' which will match if each element in the list 'Word' exists as a separate element in the list 'Z'. ie I want the output of 'T' in the following case to be T = ['Hi x']

Word = ['x']
Z = ['Hi xo xo','Hi x','yoyo','yox']

I tried the following code but it gives me all sentences with words having 'x' in it however I only want the sentences having 'x' as a separate word.

for i in Z:
    for v in i:
        if v in Word:
            print (i)

Upvotes: 0

Views: 151

Answers (5)

niemmi
niemmi

Reputation: 17273

If you would store Word as a set instead of list you could use set operations for check. Basically following splits every string on whitespace, constructs set out of words and checks if Word is subset or not.

>>> Z = ['Hi xo xo','Hi x','yoyo','yox']
>>> Word = {'x'}
>>> [s for s in Z if Word <= set(s.split())]
['Hi x']
>>> Word = {'Hi', 'x'}
>>> [s for s in Z if Word <= set(s.split())]
['Hi x']

In above <= is same as set.issubset.

Upvotes: 0

Ahasanul Haque
Ahasanul Haque

Reputation: 11164

You can do it with list comprehension.

>>> [i for i in Z if any (w.lower() ==j.lower() for j in i.split() for w in Word)]
['Hi x']

Edit:

Or you can do:

>>> [i for i in Z for w in Word if w.lower() in map(lambda x:x.lower(),i.split())]
['Hi x']

Upvotes: 1

Prashant Puri
Prashant Puri

Reputation: 2344

Just another pythonic way

[phrase for phrase in Z for w in Word if w in phrase.split()]
['Hi x']

Upvotes: 2

Thmei Esi
Thmei Esi

Reputation: 442

words = ['x']
phrases = ['Hi xo xo','Hi x','yoyo','yox']
for phrase in phrases:
    for word in words:
        if word in phrase.split():
            print(phrase)

Upvotes: 0

martin.macko.47
martin.macko.47

Reputation: 897

if you want to print all strings from Z that contain a word from Word:

Word = ['xo']
Z = ['Hi xo xo','Hi x','yoyo','yox']

res = []
for i in Z:
    for v in i.split():
        if v in Word:
            res.append(i)
            break
print(res)

Notice the break. Without the break you could get some strings from Z twice, if two words from it would match. Like the xo in the example.

The i.split() expression splits i to words on spaces.

Upvotes: 0

Related Questions