Search code examples
pythonflat

Flat list hierachy string using python


how to flat :

paths = ['[a, c, e]', '[[a, c], [a, b], d]', 'z']

To:

paths = [[a, c, e, z], [a, c, d, z] [a, b, d, z]]

Solution

    1. First, you need to convert each item to representation of list example: '["a", "c", "e"]' . To do that: you should use regex:
    import re  
    s = '[[a, c], [a, b], d]'  
    s = re.sub(r'(?<![\]\[]),', '",', re.sub(r',(?![\]\[])',',"',re.sub(r'\s*,\s*', ',', re.sub(r'(?<!\])\]', '"]',re.sub(r'\[(?!\[)', '["', s))))
    
    1. Finally, the flatten process can be described by recursive algorithm:
    def flat(x):  
        if not any(isinstance(t, list) == True for t in x):  
            return x  
        xx = []  
        for item in x:  
            if isinstance(item, str):  
                for j in range(len(xx)):  
                    xx[j].append(item)  
            else:  
                item_new = flat(item)  
                if any(isinstance(t, list) == True for t in item_new):  
                    xx.extend(item_new)  
                else:  
                    xx.append(item_new)  
        return xx