首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在python3中将列表转换为Json

如何在python3中将列表转换为Json
EN

Stack Overflow用户
提问于 2018-09-30 10:37:08
回答 1查看 4.2K关注 0票数 0

我是个初学者,刚开始学习python和数据结构。我有一个数据类型转换的问题,我需要你的帮助,我希望你能给出一个新的想法。

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

这是行数据:

代码语言:javascript
复制
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

目标风格:

代码语言:javascript
复制
{'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': []}]
           }]}
    # ··············
     ]
          }

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

代码语言:javascript
复制
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']] 

我试图将二维列表转换为相应的多维字典。

代码语言:javascript
复制
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': []}]}]}]}
    ]

目前,我一直在研究如何将这个多维度字典合并成一个多维字典。

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

EN

回答 1

Stack Overflow用户

发布于 2018-09-30 21:29:30

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

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

然后在程序开始时添加import json,最后添加以下代码:

代码语言:javascript
复制
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. 在当前行的每个字符串元素上,每一行的处理都会导致“下行对象树”。
  3. 字典的最初附加值(对于某个键)包含一个空列表。如果没有“更嵌入的”元素,这就结束了这条“路径”。
  4. 在“下行树”之前,如果程序没有在前面添加,则将一个空字典添加到此列表中。
  5. 最后一步是在与当前字符串相等的键下添加一个空数组。

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

代码语言:javascript
复制
[{"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": []}]}]
    }]
}]
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/52577109

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档