Search code examples
pythonlistedges

get list in python


#ideal nodes list should be
['A','B','C','D','E','F','G','H','I','J','K','L','M','N']

So I tried to write a definition to read the nodes and edges.Here is my code,but it seems does not work.

""" read nodes"""
def rd_nodes(a):
    nline =[line.split(":")[1].replace(';',',').split(',') for line in a]
    for i in nline:
        return i

Solution

  • itertools.combinations can help you here.

    Try this:

    from itertools import combinations
    
    s = """
    1:A,B,C,D;E,F
    2:G,H;J,K
    &:L,M,N
    """
    
    nodes = set()
    edges = set()
    
    for line in s.split():
        clusters = line.split(':')[1].split(';')
        for cluster in clusters:
            _nodes = cluster.split(',')
            nodes.update(_nodes)
            edges.update(combinations(_nodes, 2))
    

    You may use collections.OrderedDict structure for nodes and edges to maintain order if you want. Just use nodes and edges as dict keys and then at the end of the script get list of the keys.