[英]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: 如您所见,这个想法是:
res
) is a list contaning a single dictionary object. res
)是一个包含单个字典对象的列表。 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.