python - 使用python的平面列表层次结构字符串
问题描述
如何变平:
paths = ['[a, c, e]', '[[a, c], [a, b], d]', 'z']
至:
paths = [[a, c, e, z], [a, c, d, z] [a, b, d, z]]
解决方案
- 首先,您需要将每个项目转换为列表示例的表示:
'["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))))
- 最后,扁平化过程可以用递归算法来描述:
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
推荐阅读
- postgresql - Postgres:在表中插入动态数量的列和值
- java - 如何从通知或外部电子邮件深层链接到特定的 JSF 视图?
- hibernate - 指定与多个表的一对多关系
- javascript - 根据某些键合并驻留在 json 数组中的行
- html - 浏览器开发工具:CSS Grid 与 RTL 不一致
- python - 如何将 3 个单独的年(2 位)、月和日列组合成单个日期列
- c# - 如何使用 ViewportPointToLocation 在鼠标单击时检索坐标?
- r - 如何从此方框绘图 r 命令中删除异常值
- flutter - 在图像上部分覆盖卡片
- primary-key - 描述表以获取 Apache Derby 中表的主键