python - 将嵌套列表分成具有不相交元素的组

标签 python list set networkx graph-theory

我有一个看起来像这样的列表列表

my_list = [[1, 2, 3, 4], [4, 5, 6, 7], [9, 10, 11, 12]]

我想找到将列表分成两组的最佳方法,以便每组中的各个元素不重叠。例如,在上面的示例中,两组将是

group1 = [[1, 2, 3, 4], [4, 5, 6, 7]]
group2 = [[9, 10, 11, 12]]

这是因为 9、10、11、12 从未出现在 group1 的任何项目中。

最佳答案

类似于Combine lists with common elements , 解决这个问题的一种方法是从嵌套列表中定义一个图,将每个子列表视为 path , 和 寻找 connected components :

import networkx as nx

my_list = [[1, 2, 3, 4], [4, 5, 6, 7], [9, 10, 11, 12]]

G=nx.Graph()
for l in my_list:
    nx.add_path(G, l)
components = list(nx.connected_components(G))
# [{1, 2, 3, 4, 5, 6, 7}, {9, 10, 11, 12}]    

groups = []
for component in components:
    group = []
    for path in my_list:
        if component.issuperset(path):
            group.append(path)
    groups.append(group)

groups
# [[[1, 2, 3, 4], [4, 5, 6, 7]], [[9, 10, 11, 12]]]

关于python - 将嵌套列表分成具有不相交元素的组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62433896/

相关文章:

python - 如何深度复制实例属性?

javascript - jQuery,显示 <ul> 中的第一个元素

c++ - 如何正确初始化 std::set<std::string>?

java - Unirest 发布的 GZIPOutputStream 不适用于 python Flask api

python - 使用多处理后的不同结果

c# - 如何查找 List 在 List<string> 中有重复值

c++ - GCC STL_tree.h std::set 的红黑树源代码

pointers - 设置指针类型的结构域

python - Python 中的 ModbusTCP 服务器/从站实现 (pymodbus)

python - 从列表中删除空项 (Python)