如何将严格排序的字符串列表转换为字典?
我有一个严格排序的字符串列表:
['a',
'b',
'b/c',
'b/d',
'e',
'f',
'f/g',
'f/h',
'f/h/i',
'f/h/i/j']
该列表类似于树表示。因此,我需要将其转换为字典:
{'a': {},
'b': {'c': {},
'd': {}},
'e': {},
'f': {'g': {},
'h': {'i': {'j': {}}}}}
如您所见,该字典中的键是父级,值是子级。
UPD:我同意空字典比无更好
I have a strictly sorted list of strings:
['a',
'b',
'b/c',
'b/d',
'e',
'f',
'f/g',
'f/h',
'f/h/i',
'f/h/i/j']
This list is similar to tree representation. So, I need to convert it to dict:
{'a': {},
'b': {'c': {},
'd': {}},
'e': {},
'f': {'g': {},
'h': {'i': {'j': {}}}}}
As you can see, keys in this dict are parents and values are children.
UPD: I agree that empty dict is better than None
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
如果您不坚持使用
None
作为叶值,您可以使用紧凑的代码。不可否认,这段代码的作用并不明显,但它很简洁: )
If you don't insist on
None
as the leaf value, you can use the compact codeAdmittedly, it isn't that obvious what this code does, but it's succinct :)
请注意,元素不按字母顺序存储在字典中!
Note that elemts are not stored in alphabetical order in a dictionary!
希望它有帮助,递归方法:)
Hope it helps, recursive approach :)
这是我的破解方法。我反转了优化路径,因为 pop() 比 pop(0) 快得多。
像这样使用:
Here's my crack at it. I reverse the path for optimization, because pop() is much faster than pop(0).
Use like this:
这是我的决议:
this is my resolution: