如何解决如何实现一个函数来获取元素在复杂数据结构中的位置?
我使用 Python 中的列表和字典实现了以下数据结构。
data = [
{
"id": "1","children": [
{
"id": "2","children": [
{
"id": "3","children": []
}
]
}
]
},{
"id": "4","children": [
{
"id": "5","children": [
{
"id": "6","children": []
},{
"id": "7","children": [
{
"id": "8","children": []
},{
"id": "9","children": []
}
]
}
]
}
]
}
]
def get_location(id,data):
pass
因此,此函数返回一个列表,我可以使用该列表从数据中引用节点,如 -
get_location(1,data) => [0]
get_location(2,data) => [0,0]
get_location(3,0]
get_location(4,data) => [1]
get_location(5,data) => [1,0]
get_location(6,0]
get_location(7,1]
get_location(8,1,0]
get_location(9,1]
解决方法
喜欢吗?
这个返回Tuple[int]
,而不是List[int]
。但我认为元组更适合目的(也许......)。
而且,id 是 str
,而不是 int
,因为数据中 id 的类型是 str
。
from typing import Dict,Tuple,Any,Iterable
def get_location(id: str,data: Dict[str,Any])\
-> Tuple[int]:
def handler(d: Dict[str,Any],prefix: Tuple[int])\
-> Iterable[Tuple[str,Tuple[int]]]:
for i,item in enumerate(d):
yield (item['id'],(*prefix,i))
yield from handler(item['children'],i))
// you can also initialize flatten and re-use it
flatten = dict(handler(data,()))
return flatten.get(id,None)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。