2
\$\begingroup\$

I've got a list with tuples of variable length containing nodes, out of which I want to build a network:

node_list = [("one", "two"), ("eins", "zwei", "drei"),
             ("un", "deux", "trois", "quattre"), ("two", "zwei", "deux")]

Each tuple represents a subgroup in the network. I want to add each node with edges to any other member of the same tuple.

It is straightforward to use .add_edges_from(), which only expects a tuple with two nodes. For a tuple with three entries one would have to write .add_edges_from(("eins", "zwei"), ("eins", "drei"), ("zwei", "drei")). Tuples with four members require even more code.

Now I am looking for the most efficient way to populate a network given a list like node_list. My idea is:

import networkx as nx

G = nx.Graph()
for node_tuple in node_list:
    for node1 in node_tuple:
        for node2 in node_tuple:
            G.add_edge(node1, node2)

It's probably very inefficient because it sees every node twice and also adds self-loops.

\$\endgroup\$
2
  • \$\begingroup\$ Wouldn't this also create edges from each node to itself? Is that intended? \$\endgroup\$ Jun 19 '15 at 17:57
  • \$\begingroup\$ It is. Simply populating with nodes is easy, but the edges make the network. \$\endgroup\$
    – MERose
    Jun 19 '15 at 18:41
3
\$\begingroup\$

Tuples of varying lengths are a bit unusual. Perhaps those would be better as lists instead.

itertools is your friend. You can write, equivalently:

import itertools

G = nx.Graph()
for node_tuple in node_list:
    G.add_edges_from(itertools.product(node_tuple, node_tuple))

If you want to list each pair of nodes just once instead of twice, and including self-edges use itertools.combinations_with_replacement(node_tuple, 2) instead.

\$\endgroup\$
2
  • 2
    \$\begingroup\$ combinations will omit the self-edges: you need combinations_with_replacement \$\endgroup\$ Jun 19 '15 at 21:32
  • \$\begingroup\$ combinations_with_replacement() did the trick. It's also good to know that there is combinations, in case one wants self-edges. \$\endgroup\$
    – MERose
    Jun 20 '15 at 10:57

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.