使成对的相等对象生成相等对象的列表

时间:2018-12-17 10:53:45

标签: python

我有一个对象ID列表和一个表示所有对象之间相等性测试的所有可能组合的元组列表:

objects_ids=[1,2,3,4,5,6]
tests = [
    (1, 2, 0),
    (1, 3, 0),
    (1, 4, 1),
    (1, 5, 1),
    (1, 6, 0),
    (2, 3, 1),
    (2, 4, 0),
    (2, 5, 0),
    (2, 6, 0),
    (3, 4, 0),
    (3, 5, 0),
    (3, 6, 0),
    (4, 5, 1),
    (4, 6, 0),
    (5, 6, 0),
]

(1, 4, 1) - means that object #1 is equal to object #4
(1, 2, 0) - means that #1 is NOT equal to object #2

我需要生成相等对象的组,因此结果将如下所示:

[[1,4,5], [2,3], [6]]

是否有某种有效的方法?

3 个答案:

答案 0 :(得分:2)

我认为这应该可以解决问题

>>> t = [[i] + [t[1] for t in tests if t[0] == i and t[2]] + [t[0] for t in tests if t[1] == i and t[2]] for i in objects_ids]
>>> t = [list(set(k)) for k in t]
>>> t np.unique(t)
[list([1, 4, 5]) list([2, 3]) list([6])]

答案 1 :(得分:2)

这称为连接的组件。您必须添加所有节点,然后添加边缘:

import networkx as nx
G=nx.Graph()
G.add_edge(1,4)  
G.add_edge(1,5)
G.add_edge(2,3)
G.add_edge(4,5)  

for i in nx.connected_components(G):
    print(i)

输出:

{1, 4, 5}
{2, 3}
{6}

答案 2 :(得分:2)

这里是尝试:

same_objects = [i[:2] for i in tests if i[2] == 1]
main = []
for i in same_objects:
    temp = []
    for j in same_objects:
        if set(i).intersection(set(j)):
            temp.append(j)
    main.append(temp)

unique_data = [list(x) for x in set(tuple(x) for x in s)]
final_list = [list(set(sum(i, ()))) for i in unique_data]
final_list.append(list(set(objects_ids) - set(sum(final_list, []))))
print(final_list)

输出将类似于:

[[1, 4, 5], [2, 3], [6]]