python - 将平面列表转换为嵌套列表(3 级深)
问题描述
我是 Python 的新手,我正在尝试将我的平面列表数据转换为嵌套列表数据,在 stackoverflow 中找到了解决方案,但没有实现我的目标..
def build_multilevel(entries):
result = []
stack = [result]
for i, entry in enumerate(entries):
if entry == '{':
# convert last element of the top-most list on the stack
# to a new, nested list, and push that new list on top
stack[-1][-1] = [stack[-1][-1]]
stack.append(stack[-1][-1])
elif entry == '}':
stack.pop()
else:
stack[-1].append(entry)
print("File content data type is: ", type(stack))
print(len(stack))
print(stack)
return stack
我的目标是拥有这种数据:
由此:
['2019-10-09T06:57:01.605Z', 'START', 'RequestId:', 'ABC123', 'Version:', 'LATEST', '2019-10-09T06:57:01.686Z', '2019-10-09T06:57:01.685Z', 'ABC123', 'INFO', 'event.name=UAT', '2019-10-09T06:57:01.686Z', '2019-10-09T06:57:01.686Z', 'ABC123', 'INFO', '{', '"messageVersion":', '"1.0",','"invocationSource":', '"Success",','"userId":', '"User",','"requestAttributes":','{', '"type":', '"Text",', '"user-id":', '"ABC123",', '"name":', '"UATCares",','"type":', '"Media"', '},', '"machine":', '{', '"name":', '"UAT",', '"alias":', '"UAT",', '"version":', '"5"', '},','"Mode":', '"Text",', '"Intent":', '{', '"name":', '"Services",','"slots":', '{},','"slotDetails":', '{},','"confirmationStatus":', '"None"', '},', '"inputTranscript":', '"Pay', 'Serve"', '}']
对此:
['2019-10-09T06:57:01.605Z', 'START', 'RequestId:', 'ABC123', 'Version:', 'LATEST', '2019-10-09T06:57:01.686Z', '2019-10-09T06:57:01.685Z', 'ABC123', 'INFO', 'event.name=UAT', '2019-10-09T06:57:01.686Z', '2019-10-09T06:57:01.686Z', 'ABC123', 'INFO', '{',
'"messageVersion":', '"1.0",',
'"invocationSource":', '"Success",',
'"userId":', '"User",',
'"requestAttributes":',
'{',
'"type":', '"Text",',
'"user-id":', '"ABC123",',
'"name":', '"UATCares",',
'"type":', '"Media"',
'},',
'"machine":',
'{',
'"name":', '"UAT",',
'"alias":', '"UAT",',
'"version":', '"5"',
'},',
'"Mode":', '"Text",',
'"Intent":',
'{',
'"name":', '"Services",',
'"slots":', '{},',
'"slotDetails":', '{},',
'"confirmationStatus":', '"None"',
'},',
'"inputTranscript":', '"Pay', 'Serve"',
'}'
]
解决方案
推荐阅读
- python - 为什么我得到 AttributeError:模块 'networkx' 没有属性 'average_neighbor_in_degree'?
- math - 三边测量 x 分量小于实际位置的一半
- java - 通过“IN”语句选择具有 2 个字段的对象列表
- c# - 同时监控多个 IMAP 邮箱 C#
- android - Android Expandable listview 加载新数据分页
- c# - 试图让飞机在陡峭的角度上升时失去速度,在陡峭的角度下降时获得增益
- reactjs - 静态 React 项目,将值从导航菜单传递到组件,从组件传递到导航菜单
- android - SurfaceView 中是否没有控制 Android 的后退按钮的功能?
- python - kivy 应用程序在没有实现 build() 方法的情况下运行
- python - PyInstaller 生成 exe 文件错误:qt.qpa.plugin: could not load the qt platform plugin "windows" in "" 即使找到