Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/340.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

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/algorithm/10.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_Dictionary_Tree - Fatal编程技术网

Python 从列表创建嵌套树

Python 从列表创建嵌套树,python,dictionary,tree,Python,Dictionary,Tree,从列表列表中,我想创建一个嵌套字典,其中的键将指向子列表中的下一个值。此外,我还想计算子列表值序列出现的次数 例如: 从这样的列表列表中: [['a', 'b', 'c'], ['a', 'c'], ['b']] 我想创建一个嵌套字典,如下所示: { 'a': { {'b': { 'c':{} 'count_a_b_c': 1 }

从列表列表中,我想创建一个嵌套字典,其中的键将指向子列表中的下一个值。此外,我还想计算子列表值序列出现的次数

例如:

从这样的列表列表中:

[['a', 'b', 'c'],
['a', 'c'],
['b']]
我想创建一个嵌套字典,如下所示:

{
  'a': {
          {'b': 
                {
                'c':{}
                'count_a_b_c': 1
                }
            'count_a_b*': 1
          }, 
          {'c': {},
           'count_a_c': 1
          }
          'count_a*': 2
        },
  {
  'b':{},
  'count_b':1
  }
}

请注意,计数键的名称并不重要,它们的命名是为了便于说明。

我很好奇我会怎么做,并得出了以下结论:

lst = [['a', 'b', 'c'],
['a', 'c'],
['b']]

tree = {}
for branch in lst:
    count_str = 'count_*'
    last_node = branch[-1]
    cur_tree = tree
    for node in branch:
        if node == last_node:
            count_str = count_str[:-2] + f'_{node}'
        else:
            count_str = count_str[:-2] + f'_{node}_*'
        cur_tree[count_str] = cur_tree.get(count_str, 0) + 1
        cur_tree = cur_tree.setdefault(node, {})
这里没有什么特别的事

例如:

import json
print(json.dumps(tree, sort_keys=True, indent=4))
产生:

{
    "a": {
        "b": {
            "c": {},
            "count_a_b_c": 1
        },
        "c": {},
        "count_a_b_*": 1,
        "count_a_c": 1
    },
    "b": {},
    "count_a_*": 2,
    "count_b": 1
}
它并不完全重现您的想象——但这部分是因为您所期望的结果不是有效的python字典


但这可能是您解决问题的起点。

您是否尝试过实现这一目标,并与他人分享?不幸的是,我的任何尝试都没有取得成果。我确实在这个问题上花了几个小时。主要的问题是如何用for循环自动化嵌套结构…你能看看这个吗