使用 python 的平面列表层次结构字符串

Flat list hierachy string using python

如何平仓:

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

收件人:

paths = [[a, c, e, z], [a, c, d, z] [a, b, d, z]]
  1. 首先,您需要将每个项目转换为列表示例的表示形式:'["a", "c", "e"]'。为此:您应该使用 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. 最后,压扁的过程可以用递归算法来描述:
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