从两个字符串列表中查找单词的交集
Find intersection of words from two list of strings
我有两个字符串列表:
a = ['ketab khaneh','danesh gah', 'shi rin i']
b = ['ketab khaneh','dan esh gah','shirin i']
我需要列表中单个单词的交集。例如,对于上面的列表,我想要的输出是:
output = ['ketab','khaneh','gah','i']
如何在 python 中生成此输出?
使用set
交集法
a = " ".join(a).split(" ")
b = " ".join(b).split(" ")
output = list(set(a).intersection(b))
输出
['ketab', 'khaneh', 'gah', 'i']
您可以使用 set()
with itertools.chain()
and map()
实现此目的:
>>> 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'])
我有两个字符串列表:
a = ['ketab khaneh','danesh gah', 'shi rin i']
b = ['ketab khaneh','dan esh gah','shirin i']
我需要列表中单个单词的交集。例如,对于上面的列表,我想要的输出是:
output = ['ketab','khaneh','gah','i']
如何在 python 中生成此输出?
使用set
交集法
a = " ".join(a).split(" ")
b = " ".join(b).split(" ")
output = list(set(a).intersection(b))
输出
['ketab', 'khaneh', 'gah', 'i']
您可以使用 set()
with itertools.chain()
and map()
实现此目的:
>>> 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'])