首页 > 解决方案 > 将平面列表转换为嵌套列表(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"', 
    '}'
]

标签: pythonpython-3.xlistnested-lists

解决方案


推荐阅读