熊猫:删除包含相同元素的重复列表

时间:2019-11-01 07:25:10

标签: python pandas networkx graph-theory graph-algorithm

我有一些像这种形式的列表:

master_list = [[2,3,5], [3,2,5], [2,3], [2], [3], [5, 6], [5,9], [5,6,9], [9,5,6]]

master_list中的每个sub_list都是从Excel中读取的一行。列表中的数字表示route_id。

我想要获得唯一的路线组合,该组合与卡车分配相关。

所以所需的输出是:

[[2,3,5], [9,5,6]]

sub_list中的数字顺序无关紧要,但必须是包含所有route_id的部分,而不是部分。

所以我可以做:

truck_1 = [2,3,5]
truck_2 = [9,5,6]  

感谢帮助

1 个答案:

答案 0 :(得分:0)

您可以遍历所有可能的路线组合,并检查每个组合是否包含master_list中的所有项目:

from itertools import combinations, chain

all_items = set(chain.from_iterable(master_list))
combos = chain.from_iterable(combinations(master_list, i) for i in range(len(master_list)))

result = []
max_len = len(master_list)

for c in combos:
    if set(chain.from_iterable(c)) == all_items and len(c) <= max_len:
        max_len = len(c)
        result.append(c)
相关问题