Python 将平面列表转换为嵌套列表(3层深)
我是Python的新手,我正在尝试将平面列表数据转换为嵌套列表数据,在stackoverflow中找到了一个解决方案,但没有达到我的目标Python 将平面列表转换为嵌套列表(3层深),python,python-3.x,list,nested-lists,Python,Python 3.x,List,Nested Lists,我是Python的新手,我正在尝试将平面列表数据转换为嵌套列表数据,在stackoverflow中找到了一个解决方案,但没有达到我的目标 def build_multilevel(entries): result = [] stack = [result] for i, entry in enumerate(entries): if entry == '{': # convert last element of the top-mo
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"',
'}'
]
在这种情况下,看起来您需要的是词典而不是列表;你的数据来自哪里?你在读文件吗?如果是,那么就值得用
json.load()
阅读这篇文章。查看更多信息首先从哪里获得第一个列表(看起来像标记化的JSON)?我从s3 bucket获得数据,它是一个应用程序日志文件。也就是说,我需要把它转换成字典而不是列表?你能解释一下原因吗?谢谢。顺便说一下,列表中的项目用逗号隔开