我在Python中有一个长长的列表,如下所示:
myList=[
('a',[1,2,3,4,5]),
('b',[6,7,8,9,10]),
('c',[1,3,5,7,9]),
('d',[2,4,6,8,10]),
('e',[4,5,6,7,8])
]
我想详尽地列举一下这些共同的价值观
^{pr2}$四、五、六人一组也一样,直到所有的共同值都被确定(假设列表更长)
是否可以使用itertools
库或集合或以上两者的组合?在
我一直在尝试编写一个函数,在我生成的每一个新列表中循环原始列表,但效果并不理想!在
以下是我所拥有的:
def findCommonElements(MyList):
def sets(items):
for name, tuple in items:
yield name, set(tuple)
def matches(sets):
for a, b in combinations(sets, 2):
yield ':'.join([a[0], b[0]]), a[1] & b[1]
combinationsSet=list(matches(sets(keywordCount)))
combinationsList=[]
for pair,tup in combinationsSet:
setList=list(tup)
combinationsList.append((pair, len(setList), setList))
combinationsList=sorted(combinationsList,key=lambda x: x[1], reverse=True) #this just sorts the list by the number of common elements
return combinationsList
这样的怎么样?在
我想你可以试着用
itertools.combinations
和itertools.chain
这不是一个很好的例子,但应该行得通。 我将在这里使用
itertools
和生成器:或者只是
^{pr2}$itertools.combinations
下面是一个使用我刚刚创建的字典的解决方案:
使用它非常简单:
^{pr2}$还可以清理输出以匹配您想要的更多内容:
相关问题 更多 >
编程相关推荐