簡體   English   中英

將嵌套列表轉換為python中的字典

[英]convert nested list to dictionary in python

它不是一個嚴格的嵌套列表,它是一個樹形結構,看起來像:

A = [a, [b, c,[d,e]]]

相應的樹是:

                a
               / \
              b   c
                 / \                     
                 d e

只要在一個元素之后有一個子列表,該子列表就對應於該元素的子節點。 否則,元素位於同一層。 我想生成一個字典,每個節點分別作為鍵,例如:

child[a] = [b,c,d,e]
child[c] = [d,e]

我該如何在python中做到這一點? 還是在樹結構轉換方面還有其他更好的建議?

如果您將要進行大量的圖形操作,我會考慮導入networkx ,因為它將使事情變得更容易。 要將嵌套列表解析為networkx樹:

import networkx as nx

def parse_tree(node_list):
    """Parses a nested list into a networkx tree."""
    tree = nx.DiGraph()
    root = node_list[0]
    tree.add_node(root)

    queue = [(root, node_list[1])]

    while queue:
        parent, nodes = queue.pop(0)
        prev = None
        for node in nodes:
            if isinstance(node, list):
                queue.append((prev, node))
            else:
                tree.add_node(node)
                tree.add_edge(parent, node)

            prev = node

    return tree

使用此功能,很容易獲得每個節點的后代的字典:

>>> l = ["a", ["b", "c",["d","e"]]]
>>> tree = parse_tree(l)
>>> {node: nx.descendants(tree, node) for node in tree}
{'a': {'b', 'c', 'd', 'e'},
 'b': set(),
 'c': {'d', 'e'},
 'd': set(),
 'e': set()}

我仍然認為您應該使用現有的實現,並從中獲得啟發,但是如果您需要這樣做,這可能就是您正在尋找的東西:

#!/usr/bin/env python

# added a test case
B = ['a', ['b', 'c',['d','e']], 'f', ['g', 'h']]
A = ['a', ['b', 'c',['d','e']]]

# found on stack overflow - flatten list of kids for parent
def flatten(iterable):
    """Recursively iterate lists and tuples.
    """
    for elm in iterable:
        if isinstance(elm, (list, tuple)):
            for relm in flatten(elm):
                yield relm
        else:
            yield elm

# add data to an existing tree (recursive)
def treeify(tree, l):
    if isinstance(l, list):
        # avoid looking back
        l.reverse()
    for index in range(len(l)):
        if isinstance(l[index], list):
            parent_name = l[index+1]
            # flatten kids to a list
            tree[parent_name] = list(flatten(l[index]))
            # continue in deeper lists
            treeify(tree, l[index])

tree = {}
treeify(tree, A)
print tree
tree = {}
treeify(tree, B)
print tree

這會反轉list ,以免在遍歷時回頭看。 如果當前成員是list ,則Tt將名稱設置為下一個成員,並立即(遞歸)遍歷子元素。

暫無
暫無

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

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