我有一个列表列表,我想比较特定列的所有元素以查找匹配项。更具体地说,我有下表:
Item_No. features
A ['X','Y','Z']
B ['X','Y']
C ['Y']
D ['S']
我想看看项目A是否与其他项目有任何共同特征。在这种情况下,我想获得这样的东西:
Item_No. features Common
A ['X','Y','Z'] B,C
B ['X','Y'] A,C
C ['Y'] A,B
D ['S'] 0
我将如何在python上继续这个?
答案 0 :(得分:1)
def common(x,y):
"""Do list x and y have an element in common?"""
for e in x:
if e in y:
return True
return False
#listnames and their content
data = [('A',['X','Y','Z']),
('B',['X','Y']),
('C',['Y']),
('D',['S'])]
# touples of listnames and an array of listnames it
data_common = [] overlaps with
# try common on each pair of lists saving their names.
for N,A in d:
data_common.append((N,[n for n,a in data if(n is not N and common(A,a))]))
print(data_common)
输出:[('A', ['B', 'C']), ('B', ['A', 'C']), ('C', ['A', 'B']), ('D', [])]
这非常昂贵,关于O(m^2*n^2)
,m=max(len(data[,1])), n=len(data)
当然,可以对每个列表进行实际检查以进行优化
彼此两次。