简体   繁体   English

如何在python3中将List转换为Json

[英]How to convert List to Json in python3

I am a beginner and just started learning python and data structures. 我是一个初学者,刚开始学习python和数据结构。 I have a problem with data type conversion, I need your help, I hope you can give a new idea. 我在数据类型转换方面遇到问题,需要您的帮助,希望您能提出一个新的想法。

The question is to convert the string to json. 问题是将字符串转换为json。

This is row data: 这是行数据:

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

Target style: 目标风格:

{'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': []}]
           }]}
    # ··············
     ]
          }

I have successfully completed the field represented by the comma and got a complete list below. 我已经成功完成了以逗号表示的字段,并在下面获得了完整列表。

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']] 

I try to convert two-dimensional list to the corresponding multidimensional dictionary 我尝试将二维列表转换为相应的多维字典

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': []}]}]}]}
    ]

At present, I am stuck in how to merge this multiple multidimensional dictionary into a multidimensional dictionary. 目前,我陷入了如何将此多维多维字典合并为多维字典的难题。

How do I convert the current list into the style required by the question? 如何将当前列表转换为问题所需的样式?

Instead of creation of separate dictionaries and then merging them, try to create the final (joined) dictionary, without any intermediate step. 与其创建单独的词典然后合并它们,不如没有任何中间步骤,而是尝试创建最终的(联接的)词典。

The fragment of your code creating concepts list is OK. 代码创建concepts列表的片段是可以的。

Then add import json at the start of your program, and at the end, add the following code: 然后在程序的开头添加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))

As you can see, the idea is: 如您所见,这个想法是:

  1. The result ( res ) is a list contaning a single dictionary object. 结果( res )是一个包含单个字典对象的列表。
  2. Processing of each row causes "going down the object tree", on each string - element of the current row. 对每一行的处理会在每个字符串-当前行的元素上导致“向下移动对象树”。
  3. Initially added value to a dictionary (for some key) contains an empty list. 最初为字典添加的值(用于某些键)包含一个空列表。 If there is no "more embedded" element, this ends this "path". 如果没有“更多嵌入”元素,则此“路径”结束。
  4. Before "going down the tree" the program adds an empty dictionary to this list, if it has not beed added earlier. 在“下树”之前,程序会向此列表添加一个空字典(如果尚未添加)。
  5. The last step is to add an empty array, under the key equal to the current string. 最后一步是在等于当前字符串的键下添加一个空数组。

The printed result (slightly reformatted to take less rows) is: 打印结果(稍稍重新格式化以减少行数)是:

[{"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": []}]}]
    }]
}]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM