我在 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])
]
我想详尽地列举共同的价值观
('a:b', ),
('a:c', [1,3,5]),
('a:d', [2,4]),
('a:e', [4,5]),
('b:c', [7,9]),
('b:d', [6,8,10]),
('a:c:e', [5]),
('b:c:e', [7]),
('b:d:e', [6,8]),
对于四人、五人、六人的小组也是如此,直到确定所有共同值(假设列表更长)
这可能使用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