簡體   English   中英

在python中展平嵌套結構

[英]flatten nested structure in python

我該如何在Python中將其扁平化,以便每個“小部件”都是列表的元素?

{  "widgets" :[{"num": "1", "letter": "a",
              "widgets" :[{"num": "2", "letter": "b",
                           "widgets" :[{"num": "3","letter": "c"},
                                       {"num": "4", "letter": "d"}]
                         }]
            }]
}

所以最終以

[{"num":"1", "letter","a"},
 {"num": "2", "letter":"b"},
 {"num": "3", "letter":"c"},
 {"num": "4", "letter":"d"}] 

拍攝后,無論是誰提供的數據,也許都是這樣的:

def flatten_widgets(widget):
    stack = [widget['widgets']]
    while stack:
        for widget in stack.pop():
            yield {k: v for k, v in widget.items() if k != 'widgets'}
            if 'widgets' in widget:
                stack.append(widget['widgets'])

>>> list(flatten_widgets(a))

[{'letter': 'a', 'num': '1'},
 {'letter': 'b', 'num': '2'},
 {'letter': 'c', 'num': '3'},
 {'letter': 'd', 'num': '4'}]

這是一個遞歸解決方案

def flatten_widget(widget):
    assert isinstance(widget, dict)

    # Remove any sub-level widgets for processing
    widgets = widget.pop('widgets', None)

    # The first object is itself, unless it contains nothing
    flat_list = [widget] if widget else []

    # If there are sub-level widgets, flatten them
    if widgets:
        assert isinstance(widgets, list)
        # Recursively flatten each widget and add it return list
        for w in widgets:
            flat_list += flatten_widget(w)

    # Return all widgets in a list
    return flat_list

print flatten_widget(widget)
# [{'num': '1', 'letter': 'a'}, {'num': '2', 'letter': 'b'}, {'num': '3', 'letter': 'c'}, {'num': '4', 'letter': 'd'}]

請注意,它不會檢測循環參考。 它還假設您不介意原始數據結構會被修改。 我還沒有進行基准測試,但是我想不必復制每個字典項目會更快一些。

這是我的倉促回應; 寫下之后,我意識到它沒有按照您指定的順序列出列表; 但是,我認為這可能會為您指出相對於遞歸的正確方向,就像這里的其他答案一樣。

注意:未導入python模塊“優雅”。 ;)

def getflattenedwidgetlist(thislist):
    thislevellist = list()
    for dictionary in thislist:
        thisdict = dict()
        thislevellist.append(thisdict)
        for key in dictionary:
            if key != "widgets":
                thisdict[key] = dictionary[key]

        if "widgets" in dictionary:
            return getflattenedwidgetlist(dictionary["widgets"]) + [thisdict]

    return thislevellist


stuff = {
   "widgets" :[{
       "num": "1",
       "letter": "a",
       "widgets" :[{
         "num": "2",
         "letter": "b",
         "widgets" :[{
             "num": "3",
             "letter": "c"
           },
           { 
            "num": "4",
            "letter": "d"
           }]
        }]
    }] 
}

print getflattenedwidgetlist([stuff])

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM