Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/306.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/json/14.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_Json_Python 3.x_List_Dictionary - Fatal编程技术网

Python 基于字符串拆分将列表拆分为子列表

Python 基于字符串拆分将列表拆分为子列表,python,json,python-3.x,list,dictionary,Python,Json,Python 3.x,List,Dictionary,我有这样一份清单: a = [['cat1.subcat1.item1', 0], ['cat1.subcat1.item2', 'hello], [cat1.subcat2.item1, 1337], [cat2.item1, 'test']] a = [['cat1', [ ['subcat1', [ ['item1', 0], ['item2', 'hello'] ]], ['subcat2'

我有这样一份清单:

a = [['cat1.subcat1.item1', 0], ['cat1.subcat1.item2', 'hello], [cat1.subcat2.item1, 1337], [cat2.item1, 'test']]
a = [['cat1', [
        ['subcat1', [
            ['item1', 0],
            ['item2', 'hello']
        ]],
        ['subcat2', [
            ['item1', 1337]
        ]],
    ]],
    ['cat2', [
        ['item1', 'test']
    ]]
]
因此,可能有多个子类别的项目,由一个点分割。但分类的数量和深度并不是固定不变的,在各个类别之间也不相等

我希望列表如下所示:

a = [['cat1.subcat1.item1', 0], ['cat1.subcat1.item2', 'hello], [cat1.subcat2.item1, 1337], [cat2.item1, 'test']]
a = [['cat1', [
        ['subcat1', [
            ['item1', 0],
            ['item2', 'hello']
        ]],
        ['subcat2', [
            ['item1', 1337]
        ]],
    ]],
    ['cat2', [
        ['item1', 'test']
    ]]
]
我希望这是有道理的

最后,我需要一个json字符串。如果更简单,也可以直接转换为json字符串


你知道如何做到这一点吗?谢谢

您应该使用嵌套字典结构。可以使用
collections.defaultdict
functools.reduce
高效地处理此问题

可以转换为常规词典,但通常没有必要

解决方案

from collections import defaultdict
from functools import reduce
from operator import getitem

def getFromDict(dataDict, mapList):
    """Iterate nested dictionary"""
    return reduce(getitem, mapList, dataDict)

tree = lambda: defaultdict(tree)
d = tree()

for i, j in a:
    path = i.split('.')
    getFromDict(d, path[:-1])[path[-1]] = j
结果

def default_to_regular_dict(d):
    """Convert nested defaultdict to regular dict of dicts."""
    if isinstance(d, defaultdict):
        d = {k: default_to_regular_dict(v) for k, v in d.items()}
    return d

res = default_to_regular_dict(d)

{'cat1': {'subcat1': {'item1': 0,
                      'item2': 'hello'},
          'subcat2': {'item1': 1337}},
 'cat2': {'item1': 'test'}}
解释

from collections import defaultdict
from functools import reduce
from operator import getitem

def getFromDict(dataDict, mapList):
    """Iterate nested dictionary"""
    return reduce(getitem, mapList, dataDict)

tree = lambda: defaultdict(tree)
d = tree()

for i, j in a:
    path = i.split('.')
    getFromDict(d, path[:-1])[path[-1]] = j
  • getFromDict(d,path[:-1])
    获取一个列表
    path[:-1]
    ,并递归地访问与dictionary
    d
    中的列表项对应的字典值。我已经通过
    functools.reduce
    operator.getitem
    在功能上实现了这个位
  • 然后,我们从生成的字典树中访问键
    路径[-1]
    ,它是列表的最后一个元素。这将是一本字典,因为
    d
    是字典的默认目录。然后我们可以将值
    j
    分配给该字典

您应该使用嵌套字典结构。可以使用
collections.defaultdict
functools.reduce
高效地处理此问题

可以转换为常规词典,但通常没有必要

解决方案

from collections import defaultdict
from functools import reduce
from operator import getitem

def getFromDict(dataDict, mapList):
    """Iterate nested dictionary"""
    return reduce(getitem, mapList, dataDict)

tree = lambda: defaultdict(tree)
d = tree()

for i, j in a:
    path = i.split('.')
    getFromDict(d, path[:-1])[path[-1]] = j
结果

def default_to_regular_dict(d):
    """Convert nested defaultdict to regular dict of dicts."""
    if isinstance(d, defaultdict):
        d = {k: default_to_regular_dict(v) for k, v in d.items()}
    return d

res = default_to_regular_dict(d)

{'cat1': {'subcat1': {'item1': 0,
                      'item2': 'hello'},
          'subcat2': {'item1': 1337}},
 'cat2': {'item1': 'test'}}
解释

from collections import defaultdict
from functools import reduce
from operator import getitem

def getFromDict(dataDict, mapList):
    """Iterate nested dictionary"""
    return reduce(getitem, mapList, dataDict)

tree = lambda: defaultdict(tree)
d = tree()

for i, j in a:
    path = i.split('.')
    getFromDict(d, path[:-1])[path[-1]] = j
  • getFromDict(d,path[:-1])
    获取一个列表
    path[:-1]
    ,并递归地访问与dictionary
    d
    中的列表项对应的字典值。我已经通过
    functools.reduce
    operator.getitem
    在功能上实现了这个位
  • 然后,我们从生成的字典树中访问键
    路径[-1]
    ,它是列表的最后一个元素。这将是一本字典,因为
    d
    是字典的默认目录。然后我们可以将值
    j
    分配给该字典

    • 他们的解决方案不如@jpp漂亮,但至少我试过了。使用
      merge
      函数合并深度dict,如中所示


      不像@jpp他们的解决方案那么漂亮,但至少我试过了。使用
      merge
      函数合并深度dict,如中所示


      到目前为止你试过什么?在我看来,它更像是一个dict(of dict(~ of dict)),因为您似乎有键/值对。你能有多个不同值的
      'cat1'
      项吗?如果你想在末尾使用json,我建议使用字典而不是嵌套列表。当然,你是对的,它的dicts of dicts等等:)到目前为止你做了哪些尝试?在我看来,它更像是一个dict(of dict(~ of dict)),因为您似乎有键/值对。你能有多个不同值的
      'cat1'
      项吗?如果你想在末尾使用json,我建议使用字典而不是嵌套列表。当然,你是对的,它的dicts of dicts等等:)