[英]Python splitting lists to intersections iteratively
我想做的是根據它們的共同元素來拆分一些列表,並帶有它們來自哪個列表的標識符。 因此,首先構建一個包含所有列表中所有公共項目的列表,然后構建一個包含列表子集中存在的項目的列表等。
最好用一個例子來解釋一下:
list A : [ 2, 4, 6, 8, 10 ]
list B : [ 2, 6, 10, 11 , 13 ]
list C : [ 3, 6, 8, 9 , 11 ]
===> OUTPUT :
( [ A, B, C ] : [6] ) ,
( [ A, B ] : [ 2, 10 ] ) ,
( [ A, C ] : [ 8 ] )
( [ B, C ] : [ 11 ] ) ,
( [ A ] : [ 4 ] ) ,
( [ B ] : [ 13] ) ,
( [ C ] : [ 3 , 9 ]
我可以在紙上找到解決該問題的方法:
A&B = [2,6,10], A = [ 4,8] , B = [ 11,13 ]
A&B&C = [ 6 ]
交集,現在A&B becomes [ 2, 10 ]
2,10 A&B becomes [ 2, 10 ]
。 但是上面的內容對我來說似乎並不那么Python-我是Python的新用戶。 我可以使用任何庫來幫助我嗎? 我計划使用python 2.7,但是如果要使用Python 3可以幫助我,我可以這樣做。
你在參加編程比賽嗎?
>>> A=[ 2, 4, 6, 8, 10 ]
>>> B =[ 2, 6, 10, 11 , 13 ]
>>> C =[ 3, 6, 8, 9 , 11 ]
>>> r=set(A+B+C)
>>> l=[[] for i in r]
>>> for index,i in enumerate(r):
add=[]
if i in A:
add.append("a")
if i in B:
add.append("b")
if i in C:
add.append("c")
l[index].extend(add)
>>> d={}
>>> for i in r:
d[i]=0
>>> for index,i in enumerate(d):
d[i]=l[index]
>>> final={}
>>> for i in d.values():
final[tuple(i)]=[]
>>> for k,v in d.items():
final[tuple(v)].append(k)
>>> final
{('c',): [3, 9], ('a',): [4], ('a', 'c'): [8], ('a', 'b'): [2, 10], ('a', 'b', 'c'): [6], ('b', 'c'): [11], ('b',): [13]}
>>>
我沒有足夠的聲譽來發表評論,而且我敢肯定這不是做到這一點的最佳方法,但可以幫上忙。
如果您從將每個列表與一個字母相關聯的字典開始:
lists = {
'A' : [2,4,6,8,10],
'B' : [2,6,10,11,13],
'C' : [3,6,8,9,11]
}
然后,您可以使用類似的內容來映射出現的內容(如果您不熟悉defaultdict或collections庫將其簽出,那就太好了)
from collections import defaultdict
occurrences = defaultdict(list)
for letter, values in lists.items():
for value in values:
occurrences[value].append(letter)
然后您使用另一個字典將出現的字典按值分組
result = defaultdict(list)
for value, letters in occurrences.items():
result[tuple(letters)].append(value)
你得到
{('A',): [4],
('A', 'B'): [2, 10],
('A', 'B', 'C'): [6],
('A', 'C'): [8],
('B',): [13],
('B', 'C'): [11],
('C',): [3, 9]}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.