输入:
input_list=['1.exe','2.exe','3.exe','4.exe']
输出格式:
out_dict=[{'name':'1.exe',
'children':[{'name':'2.exe',
'children':[{'name':'3.exe
'children':[{'name':'4.exe'}]}}}]
输入是上面提到的列表,我们必须以上面几行中提到的格式获取输出。
我尝试使用嵌套的for循环,但是它不起作用。我们如何在其中实现JSON
?
答案 0 :(得分:1)
input_list=['1.exe','2.exe','3.exe','4.exe']
def split(data):
try:
first_value = data[0]
data = [{'name': first_value, 'children': split(data[1:])} if split(data[1:]) != [] else {'name': first_value}]
return data
except:
return data
print (split(input_list))
输出:
[{'name': '1.exe', 'children':
[{'name': '2.exe', 'children':
[{'name': '3.exe', 'children':
[{'name': '4.exe'}]}]}]}]
更容易理解的代码(带有解释):
input_list=['1.exe','2.exe','3.exe','4.exe']
def split(input_list):
if len(input_list) == 0:
return input_list # if there is no data return empty list
else: # if we have elements
first_value = input_list[0] # first value
if split(input_list[1:]) != []: # data[1:] will return a list with all values except the first value
input_list = [{'name':first_value ,'children': split(input_list[1:])}]
return input_list # return after the last recursion is called
else:
input_list = [{'name': first_value}]
return input_list
print (split(input_list))
输出:
[{'name': '1.exe', 'children':
[{'name': '2.exe', 'children':
[{'name': '3.exe', 'children':
[{'name': '4.exe'}]}]}]}]
或:
input_list=['1.exe','2.exe','3.exe','4.exe']
def split(input_list):
if input_list:
head, *tail = input_list # This is a nicer way of doing head, tail = data[0], data[1:]
if split(tail) != []:
return [{'name': head, 'children':split(tail)}]
else:
return [{'name': head}]
else:
return {}
print (split(input_list))
从Python转换为JSON:
import json # a Python object (dict): x = { "name": "John", "age": 30, "city": "New York" } # convert into JSON: y = json.dumps(x) # the result is a JSON string: print(y)
JSON是用于存储和交换数据的语法。从Python转换 到JSON如果您有Python对象,则可以将其转换为JSON 使用json.dumps()方法输入字符串。
import json
input_list=['1.exe','2.exe','3.exe','4.exe']
def split(input_list):
try:
first_value = input_list[0]
input_list = {'name': first_value, 'children': split(input_list[1:])} if split(input_list[1:]) != [] else {'name': first_value}
return input_list
except:
return input_list
data = split(input_list)
print (json.dumps(data))