sam
sam

Reputation: 19164

string comparison on 2 lists

I have 2 lists.

a = ['this;mango', 'is:red', 'test;cat']
b = ['man', 'is', 'can']

I want to iterate each element of b and check if that string is present in list a. How can i do that ?

for above example output will be:

# is

Upvotes: 1

Views: 105

Answers (6)

dugres
dugres

Reputation: 13087

You can combine b's elements to avoid a second loop :

import re

a = ['this;mango', 'is:red', 'test;cat']
b = ['man', 'is', 'can']


def words_in_strings(words, strings):
    pat = re.compile('|'.join(words))
    for i in strings:
        m = pat.search(i)
        if m:
            yield m.group(0)

for i in words_in_strings(b, a):
    print i

Upvotes: 1

Hui Zheng
Hui Zheng

Reputation: 10224

How about this?

[i for i in b if any(i in re.split(r'\W', j) for j in a)]

Upvotes: 1

sotapme
sotapme

Reputation: 4903

Taking @NPE's solution and hoping non-word chars \W is OK.

In [221]: a = ['this;mango', 'is:red', 'test;cat']

In [222]: right = set(reduce(operator.add, list(re.split(r'[\W]', s) for s in a)))

In [223]: right
Out[223]: set(['this', 'is', 'cat', 'mango', 'test', 'red'])

In [224]: left = set(['man', 'is', 'can'])

In [225]: left
Out[225]: set(['is', 'can', 'man'])

In [226]: left &  right
Out[226]: set(['is'])

Upvotes: 1

Rohit Jain
Rohit Jain

Reputation: 213203

a = ['this;mango', 'is:red', 'test;cat']
b = ['man', 'is', 'can']

import re

for elem in b:
    for test in a:
        if re.search(r'\b' + re.escape(elem) + r'\b', test):
            print elem

Using List Comprehension:

>>> a = ['this;mango', 'is:red', 'test;cat']
>>> b = ['man', 'is', 'can']
>>> 
>>> import re
>>> [elem for elem in b if any(re.search(r'\b' + re.escape(elem) + r'\b', test) for test in a)]
['is']

Another version with map and lambda to avoid the explicit loop over a:

>>> [elem for elem in b if any(map(lambda test: re.search(r'\b' + re.escape(elem) + r'\b', test), a))]
['is']

Upvotes: 2

user2070336
user2070336

Reputation:

I think you really have to specify your seperators in a, otherwise "man" should also be found.

>>> a = ['this;mango', 'is:red', 'test;cat']
>>> b = ['man', 'is', 'can']
>>> [elem for elem in b if elem in " ".join(a)]
['man', 'is']

Upvotes: 1

NPE
NPE

Reputation: 500177

In [13]: words = set(reduce(operator.add, (re.split(r'[:;]', s) for s in a)))

In [14]: words
Out[14]: set(['this', 'is', 'cat', 'mango', 'test', 'red'])

In [15]: [w for w in b if w in words]
Out[15]: ['is']

Upvotes: 1

Related Questions