首页 > 解决方案 > 使用python的平面列表层次结构字符串

问题描述

如何变平:

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

至:

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

标签: pythonflat

解决方案


  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  

推荐阅读