Python 从单个嵌套列表中获取交点?
我有以下嵌套列表:Python 从单个嵌套列表中获取交点?,python,python-3.x,data-structures,itertools,Python,Python 3.x,Data Structures,Itertools,我有以下嵌套列表: list_ = [['The'], ['The', 'fox', 'quick'], ['quick', 'the'], ['dog']] 如何有效地计算每个子列表之间的交集 ['the', 'quick'] 我试图: list(itertools.product([for e in [list_]])) 首先,对列表进行预处理,使所有单词小写: list_ = [set(word.lower() for word in item) for item in list_]
list_ = [['The'], ['The', 'fox', 'quick'], ['quick', 'the'], ['dog']]
如何有效地计算每个子列表之间的交集
['the', 'quick']
我试图:
list(itertools.product([for e in [list_]]))
首先,对列表进行预处理,使所有单词小写:
list_ = [set(word.lower() for word in item) for item in list_]
然后要使用itertools.compositions
和set()
操作:
results = [x&y for x,y in itertools.combinations(list_,2)]
# [{'the'}, {'the'}, set(), {'the', 'quick'}, set(), set()]
首字母列表中的单词小写:
l = [set(map(str.lower, sub)) for sub in list_]
创建列表中所有单词的唯一集合:
s = set(i for sub in l for i in sub)
>>> list(set(list_[0]).intersection(*list_[1:]))
['the', 'fox']
过滤掉它们:
r = [i for i in s if all(i in sub for sub in l)]
现在
r
包含属于所有子列表的成员。首先,将所有内容小写并创建集合:
list_ = [['The', 'fox'], ['The', 'fox', 'quick'], ['lazy','quick', 'the', 'fox'], ['fox', 'the', 'dog']]
list2 = [{item.lower() for item in l} for l in list_]
然后使用集合操作,从第一个集合开始:
i = iter(list2)
result = next(i)
for s in i:
result &= s
结果是{'The','fox'}
。如果需要列表而不是集合,可以将其发送到list()
函数。注意,在这里使用集合将产生任意顺序
>>> result
{'the', 'fox'}
>>> list(result)
['the', 'fox']
首先对所有字符串应用lower:
>>> list_ = map(lambda l: map(lambda w: w.lower(), l), list_)
第二,将第一个列表与其余列表相交:
s = set(i for sub in l for i in sub)
>>> list(set(list_[0]).intersection(*list_[1:]))
['the', 'fox']
将内部列表中的所有元素转换为大写。见资本输出清单
在所有共享内部列表中查找所有共享元素:将所有内部列表转换为集合,并使用交集获取共享元素是否要所有成对交集的列表?@DYZ谢谢,是的!输出没有意义。类似于
[['the'],['quick'],[]
的东西会更有意义。谢谢@wim I updated.@john doe不,的
与的
不同,但是你可以通过将所有单词转换成小写来实现它们。我注意到输出是:[{'the'},set(),set(),{'quick'},set(),set()]
。虽然它实际上是对的,但我想留下一个简单的列表:['The'quick']
。我尝试按如下方式删除空集:list2=[x for x in list1 if x!={}]
实际上,{'the'},set(),set(),{'quick'},set(),set(),
是正确的答案。我得到了一个异常:TypeError:'map'对象不可下标
Opps,我没有看到python-3.x标记。这是Python2的答案。将list()
扔到每个map
s周围。