이것은 기본 플랫 요소, 일명 입력 데이터입니다.
['a-ab-aba-abaa-abaaa', 'a-ab-aba-abab', 'a-ac-aca-acaa', 'a-ac-aca-acab']
이것은 내가 필요한 대상 데이터, 일명 출력 데이터입니다.
[
{
"title": "a",
"children": [
{
"title": "ab",
"children": [
{
"title": "aba",
"children": [
{
"title": "abaa",
"children": [
{
"title": "abaaa"
}
]
},
{
"title": "abab"
}
]
}
]
},
{
"title": "ac",
"children": [
{
"title": "aca",
"children": [
{
"title": "acaa"
},
{
"title": "acab"
}
]
}
]
}
]
}
]
나는이 json 데이터를 생성하기 위해 deep-for-loop 반복을 사용할 수 있다고 생각했지만 레벨 수가 10보다 클 것이기 때문에 너무 어렵습니다. 그래서 for-loop는이 과정에서 할 수 없다고 생각합니다. 이 목표를 달성하기 위해 패키지 코드를 사용하여 함수를 구현 하시겠습니까? 당신의 마음가짐을 공유 해주셔서 감사합니다. 신의 축복이 있기를!
다음은 itertools를 사용하는 재귀 솔루션입니다. 이것이 귀하의 목적에 충분히 효율적인지 모르겠지만 작동합니다. 문자열 목록을 목록 목록으로 변환 한 다음 동일한 첫 번째 키가있는 목록으로 나눈 다음 사전을 빌드하고 첫 번째 키를 제거한 상태에서 반복하는 방식으로 작동합니다.
from itertools import groupby
from pprint import pprint
data = ['a-ab-aba-abaa-abaaa', 'a-ab-aba-abab', 'a-ac-aca-acaa', 'a-ac-aca-acab']
components = [x.split("-") for x in data]
def build_dict(component_list):
key = lambda x: x[0]
component_list = sorted(component_list, key=key)
# divide into lists with the same fist key
sublists = groupby(component_list, key)
result = []
for name, values in sublists:
value = {}
value["title"] = name
value["children"] = build_dict([x[1:] for x in values if x[1:]])
result.append(value)
return result
pprint(build_dict(components))
산출:
[{'children': [{'children': [{'children': [{'children': [{'children': [],
'title': 'abaaa'}],
'title': 'abaa'},
{'children': [], 'title': 'abab'}],
'title': 'aba'}],
'title': 'ab'},
{'children': [{'children': [{'children': [], 'title': 'acaa'},
{'children': [], 'title': 'acab'}],
'title': 'aca'}],
'title': 'ac'}],
'title': 'a'}]
이 사전을 json으로 변환하려면 json.dumps
json 모듈에서 사용할 수 있습니다 . 내 탐험이 명확하기를 바랍니다.
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다