pythongraphlogicnetworkx

networkx graph get groups of linked/connected values with multiple values


If I use such data

import networkx as nx

G = nx.Graph()
G.add_nodes_from([1, 2, 3, 4, 5, 6, 7])
G.add_edges_from([(1, 2), (1, 3), (2, 4), (5, 6)])
print(list(nx.connected_components(G)))

Everything works fine.

But what if I need to get connected values from multiple tuple, such as the folowing

import networkx as nx

G = nx.Graph()
G.add_nodes_from([1, 2, 3, 4, 5, 6, 7])
G.add_edges_from([(1, 2), (1, 3, 7), (2, 4, 1, 6), (5, 6)])
print(list(nx.connected_components(G)))

As you can see its not classic and not working. What methods can I implement in order to pass such data, so that I got connected array values?

I expect getting arrays with connected values between each other


Solution

  • The issue is that add_edges_from only takes a list of (source, target) tuples.

    You could use itertools:

    import networkx as nx
    from itertools import chain, pairwise
    
    G = nx.Graph()
    G.add_nodes_from([1, 2, 3, 4, 5, 6, 7])
    
    edges = [(1, 2), (1, 3, 7), (2, 4, 1, 6), (5, 6)]
    G.add_edges_from(chain.from_iterable(map(pairwise, edges)))
    
    print(list(nx.connected_components(G)))
    

    Variant without import:

    G.add_edges_from(e for t in edges for e in zip(t, t[1:]))
    

    Output:

    [{1, 2, 3, 4, 5, 6, 7}]
    

    Graph:

    enter image description here

    Intermediates:

    # list(chain.from_iterable(map(pairwise, edges)))
    # [e for t in edges for e in zip(t, t[1:])]
    
    [(1, 2), (1, 3), (3, 7), (2, 4), (4, 1), (1, 6), (5, 6)]