【问题标题】:How to convert List to Json in python3如何在python3中将List转换为Json
【发布时间】:2019-03-05 17:41:04
【问题描述】:

我是初学者,刚开始学习 Python 和数据结构。 遇到数据类型转换的问题,需要你的帮助,希望你能给点新思路。

问题是将字符串转换为json。

这是行数据:

machine learning,inear model,linear regression,least squares
,neural network,neuron model,activation function
,multi-layer network,perceptron
,,,connection right
,reinforcement learning,model learning,strategy evaluation
,,,strategy improvement
,,model-free learning,monte carlo method
,,,time series learning
,imitate learning,directly imitate learning
,,,inverse reinforcement learning

目标样式:

{'machine learning':
    [{'inear model':
        [{'linear regression':
            [{'least squares': []}]
          }]},
    {'neural network':
        [{'neuron model':
              [{'activation function': []}]
          }]},
    {'multi-layer network':
         [{'perceptron':
               [{'connection right': []}]
           }]},
    {'reinforcement learning':
         [{'model learning':
               [{'strategy evaluation': []}]
           }]}
    # ··············
     ]
          }

我已经成功完成了逗号所代表的字段,并得到了下面的完整列表。

with open('concept.txt', 'r') as f:
    contents = f.readlines()
concepts = []

for concept in contents:
    concept = concept.replace('\n', '')
    array = concept.split(',')
    concepts.append(array)

for i in range(len(concepts)):
    for j in range(len(concepts[i])):
        if concepts[i][j] == '':
            concepts[i][j] = concepts[i-1][j]
print(concepts)


>>> [['machine learning', ' linear model', ' linear regression', ' least squares'], 
    ['machine learning', ' neural network', ' neuron model', ' activation function'],
    ['machine learning', ' multi-layer network', ' perceptron'], 
    ['machine learning', ' multi-layer network', ' perceptron', ' connection right'], 
    ['machine learning', ' reinforcement learning', ' model learning', ' strategy evaluation'], 
    ['machine learning', ' reinforcement learning', ' model learning', ' strategy improvement'], 
    ['machine learning', ' reinforcement learning', ' model-free learning', ' Monte Carlo method'], 
    ['machine learning', ' reinforcement learning', ' model-free learning', 'time series learning'], 
    ['machine learning', ' imitate learning', ' directly imitate learning'], 
    ['machine learning', ' imitate learning', ' directly imitate learning', ' inverse reinforcement learning']] 

我尝试将二维列表转换为对应的多维字典

def dic(list):
    key = list[0]
    list.pop(0)
    if len(list) == 0:
        return {key: []}
    return {key: [dic(list)]}

def muilti_dic(mlist):
    muilti_list = []
    for i in range(len(mlist)):
        dic = dic(mlist[i])
        muilti_list.append(dic)
    return muilti_list

>>> [
     {'machine learning': 
         [{'inear model': 
          [{'linear regression': [{'least squares': []}]}]}]}, 
     {'machine learning': 
        [{'neural network': 
          [{'neuron model': [{'activation function': []}]}]}]}, 
     {'machine learning': 
        [{'multi-layer network': [{'perceptron': []}]}]}, 
     {'machine learning': 
        [{'multi-layer network': 
          [{'perceptron': [{'connection right': []}]}]}]}, 
     {'machine learning': 
        [{'reinforcement learning': 
          [{'model learning': [{'strategy evaluation': []}]}]}]}, 
     {'machine learning': 
        [{'reinforcement learning': 
          [{'model learning': [{'strategy improvement': []}]}]}]}, 
     {'machine learning': 
        [{'reinforcement learning': 
          [{'model-free learning': [{'Monte Carlo method': []}]}]}]}, 
     {'machine learning': 
        [{'reinforcement learning': 
          [{'model-free learning': [{'time series learning': []}]}]}]}, 
     {'machine learning': 
        [{'imitate learning': [{'directly imitate learning': []}]}]}, 
     {'machine learning': [{'imitate learning': [{'directly imitate learning': [{'inverse reinforcement learning': []}]}]}]}
    ]

目前,我陷入了如何将这个多维字典合并为多维字典的问题。

如何将当前列表转换为问题所需的样式?

【问题讨论】:

标签: python data-structures data-transfer


【解决方案1】:

而不是创建单独的字典然后合并它们, 尝试创建最终(加入)字典,无需任何中间步骤。

创建concepts 列表的代码片段是可以的。

然后在程序的开头添加import json,并在末尾添加, 添加以下代码:

res = []    # Result
for row in concepts:
    curr = res    # Current object
    for str in row:
        if len(curr) == 0:
            curr.append({})
        curr = curr[0]
        if str not in curr:
            curr[str] = []
        curr = curr[str]

print(json.dumps(res, indent=2))

如您所见,这个想法是:

  1. 结果 (res) 是一个包含单个字典对象的列表。
  2. 处理每一行都会导致“对象树向下”,在每个 string - 当前行的元素。
  3. 最初添加到字典的值(对于某些键)包含一个空列表。 如果没有“更多嵌入”元素,则结束此“路径”。
  4. 在“下树”之前,程序会在此列表中添加一个空字典, 如果之前没有添加。
  5. 最后一步是在等于当前字符串的键下添加一个空数组。

打印结果(稍微重新格式化以减少行数)是:

[{"machine learning": [{
    "inear model": [{
      "linear regression": [{
        "least squares": []}]}],
    "neural network": [{
      "neuron model": [{
        "activation function": []}]}],
    "multi-layer network": [{
      "perceptron": [{
        "connection right": []}]}],
    "reinforcement learning": [{
      "model learning": [{
        "strategy evaluation": [],
        "strategy improvement": []}],
      "model-free learning": [{
        "monte carlo method": [],
        "time series learning": []}]}],
    "imitate learning": [{
      "directly imitate learning": [{
        "inverse reinforcement learning": []}]}]
    }]
}]

【讨论】:

    猜你喜欢
    • 2015-10-01
    • 2012-12-23
    • 2015-06-05
    • 2014-08-12
    • 2020-09-15
    • 1970-01-01
    • 2014-09-09
    • 2019-05-08
    • 2017-03-29
    相关资源
    最近更新 更多