gpt4 book ai didi

python - 将列表中的一组 URL 表示为树结构

转载 作者:太空狗 更新时间:2023-10-30 01:23:57 26 4
gpt4 key购买 nike

我有一个存储 URL 的字典列表。它只有两个字段,titleurl。示例:

[
{'title': 'Index Page', 'url': 'http://www.example.com/something/index.htm'},
{'title': 'Other Page', 'url': 'http://www.example.com/something/other.htm'},
{'title': 'About Page', 'url': 'http://www.example.com/thatthing/about.htm'},
{'title': 'Detail Page', 'url': 'http://www.example.com/something/thisthing/detail.htm'},
]

但是,我想从这个字典列表中得到一个树结构。我正在寻找这样的东西:

{ 'www.example.com': 
[
{ 'something':
[
{ 'thisthing':
[
{ 'title': 'Detail Page', 'url': 'detail.htm'}
]
},
[
{ 'title': 'Index Page', 'url': 'index.htm'},
{ 'title': 'Other Page', 'url': 'other.htm'}
]
]
},
{ 'thatthing':
[
{ 'title': 'About Page', 'url': 'about.htm'}
]
}
]
}

我的第一次尝试是在一堆 for 循环中使用 urlparse 汤,我相信有更好更快的方法来做到这一点。

我看到有人在 SO 上使用列表推导式、lambda 函数等施展魔法。我仍在探索中。

(对于 Django 开发人员:我将使用我的 Django 应用程序。我将 URL 存储在一个名为 Page 的模型中,该模型有两个字段 name标题)

最佳答案

第三次是魅力...那是你那里的一些不错的结构 :)。在您的评论中,您提到您“无法想出更好的树格式来表示这样的数据”......这让我再次冒昧地(稍微)改变了输出的格式化。为了动态添加子元素,必须创建一个字典来容纳它们。但是对于“叶节点”,这个字典永远不会被填充。如果需要的话,这些当然可以被另一个循环删除,但它不会在迭代过程中发生,因为空的 dict 应该存在于可能的新节点。 some 适用于没有文件的节点:这些节点将包含一个空的 list

ll = [
{'title': 'Index Page', 'url': 'http://www.example.com/something/index.htm'},
{'title': 'Other Page', 'url': 'http://www.example.com/something/other.htm'},
{'title': 'About Page', 'url': 'http://www.example.com/thatthing/about.htm'},
{'title': 'Detail Page', 'url': 'http://www.example.com/something/thisthing/detail.htm'},
]

# First build a list of all url segments: final item is the title/url dict
paths = []
for item in ll:
split = item['url'].split('/')
paths.append(split[2:-1])
paths[-1].append({'title': item['title'], 'url': split[-1]})

# Loop over these paths, building the format as we go along
root = {}
for path in paths:
branch = root.setdefault(path[0], [{}, []])
for step in path[1:-1]:
branch = branch[0].setdefault(step, [{}, []])
branch[1].append(path[-1])

# As for the cleanup: because of the alternating lists and
# dicts it is a bit more complex, but the following works:
def walker(coll):
if isinstance(coll, list):
for item in coll:
yield item
if isinstance(coll, dict):
for item in coll.itervalues():
yield item

def deleter(coll):
for data in walker(coll):
if data == [] or data == {}:
coll.remove(data)
deleter(data)

deleter(root)

import pprint
pprint.pprint(root)

输出:

{'www.example.com':
[
{'something':
[
{'thisthing':
[
[
{'title': 'Detail Page', 'url': 'detail.htm'}
]
]
},
[
{'title': 'Index Page', 'url': 'index.htm'},
{'title': 'Other Page', 'url': 'other.htm'}
]
],
'thatthing':
[
[
{'title': 'About Page', 'url': 'about.htm'}
]
]
},
]
}

关于python - 将列表中的一组 URL 表示为树结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7794489/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com