Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/user-interface/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在python中将嵌套列表转换为字典_Python_List_Parsing_Dictionary_Tree - Fatal编程技术网

在python中将嵌套列表转换为字典

在python中将嵌套列表转换为字典,python,list,parsing,dictionary,tree,Python,List,Parsing,Dictionary,Tree,它不是一个严格的嵌套列表,它是一个树结构,看起来像: A = [a, [b, c,[d,e]]] 对应的树是: a / \ b c / \ d e 每当一个元素后面有一个子列表时,该子列表对应于该元素的子节点。否则,元素位于同一层。我想生成一个字典,每个节点分别作为一个键,如: child[

它不是一个严格的嵌套列表,它是一个树结构,看起来像:

A = [a, [b, c,[d,e]]]
对应的树是:

                a
               / \
              b   c
                 / \                     
                 d e
每当一个元素后面有一个子列表时,该子列表对应于该元素的子节点。否则,元素位于同一层。我想生成一个字典,每个节点分别作为一个键,如:

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

在python中如何实现这一点?或者对于树结构转换还有其他更好的建议吗?

我仍然认为您应该使用现有的实现/从中获得灵感,但如果您需要这样做,这可能就是您想要的:

#!/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

这将反转
列表
,以避免在遍历它时向后看。如果当前成员是
列表,Tt将名称设置为下一个成员,并立即(递归地)遍历子元素。

我仍然认为您应该使用现有的实现/从现有的实现中获得灵感,但如果您需要此实现,这可能就是您想要的:

#!/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

这将反转
列表
,以避免在遍历它时向后看。如果当前成员是
列表,Tt将名称设置为下一个成员,并立即(递归地)遍历子元素。

我仍然认为您应该使用现有的实现/从现有的实现中获得灵感,但如果您需要此实现,这可能就是您想要的:

#!/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

这将反转
列表
,以避免在遍历它时向后看。如果当前成员是
列表,Tt将名称设置为下一个成员,并立即(递归地)遍历子元素。

我仍然认为您应该使用现有的实现/从现有的实现中获得灵感,但如果您需要此实现,这可能就是您想要的:

#!/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

这将反转
列表
,以避免在遍历它时向后看。TT如果当前的代码是<代码>列表>代码,将其命名为下一个成员,并立即(递归地)遍历子元素。

如果要进行大量的图形操作,我会考虑导入<代码> 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()}

如果你要做很多图表操作,我会考虑导入<代码> 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()}

如果你要做很多图表操作,我会考虑导入<代码> 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()}

如果你要做很多图表操作,我会考虑导入<代码> 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()}

重复的键会发生什么情况,比如
[a[b,a[d,e]]]
?结果如何?尝试使用树的现有实现并使用它。@ReutSharabani感谢Reut。所有的元素都是不同的。在重复的键上会发生什么,比如
[a[b,a[d,e]]]
?结果如何?尝试使用树的现有实现并使用它。@ReutSharabani感谢Reut。所有的元素都是不同的。在重复的键上会发生什么,比如
[a[b,a[d,e]]]
?结果如何?尝试使用树的现有实现并使用它。@ReutSharabani感谢Reut。所有的元素都是不同的。在重复的键上会发生什么,比如
[a[b,a[d,e]]]
?结果如何?尝试使用树的现有实现并使用它。@ReutSharabani感谢Reut。所有元素都是不同的。