Reputation: 45
I have two list of strings as:
a = ['ketab khaneh','danesh gah', 'shi rin i']
b = ['ketab khaneh','dan esh gah','shirin i']
I need the intersection of individual words from the list. For example, for above lists, my desired output is:
output = ['ketab','khaneh','gah','i']
How I can produce this output in python?
Upvotes: 0
Views: 624
Reputation: 9047
use set
intersection method
a = " ".join(a).split(" ")
b = " ".join(b).split(" ")
output = list(set(a).intersection(b))
output
['ketab', 'khaneh', 'gah', 'i']
Upvotes: 2
Reputation: 48077
You can achieve this using set()
with itertools.chain()
and map()
as:
>>> from itertools import chain
>>> a=['ketab khaneh','danesh gah', 'shi rin i']
>>> b=['ketab khaneh','dan esh gah','shirin i']
>>> set(chain(*map(str.split, a))).intersection(chain(*map(str.split, b)))
set(['i', 'khaneh', 'ketab', 'gah'])
Upvotes: 2