def dothier(seq, sep='.'):
"""Generate path from dot-strings in order for creation
tree: first - parents then children:
>>> for x in dothier(["x.y.z", "a"]): print x, x.leaf
a True
x False
x.y False
x.y.z True
Every returned string (unicode) has flag - leaf
"""
# returns this, as unicode but with flag leaf
_Node = type("dothier_node", (unicode,), {"leaf":False})
seq = sorted(seq)
mem = set()
for p in seq:
spl = p.split(sep)
for ip in xrange(1, len(spl) + 1):
pp = _Node(sep.join(spl[:ip]))
if len(spl) == 1 or ip == len(spl):
pp.leaf = True
if not pp in mem:
yield pp
mem.add(pp)
def dottree(seq, sep='.', fullpath=False):
"""Returns dict of dicts like tree from sequence of dot separated strings.
For example,
>>> dottree(["x.y.z", "x.y", "a", "a.b.c", "a.b"])
{'a': {'b': {'c': {}}}, 'x': {'y': {'z': {}}}}
and
>>> dottree(["x.y.z", "x.y", "a", "a.b.c", "a.b"], fullpath=True)
{'a': {'a.b': {'a.b.c': {}}}, 'x': {'x.y': {'x.y.z': {}}}}
"""
def ins(map, path):
d = map
parents = []
for p in path:
if fullpath:
key = sep.join(parents + [p])
else:
key = p
d = d.setdefault(key, {})
parents.append(p)
ret = {}
seq = sorted(seq)
for p in seq:
pp = p.split(sep)
if not pp:
continue
ins(ret, pp)
return ret
Examples of usage are... in it's docstrings :) They are useful in GUI application: to construct tree or another hierarchical controls from paths (retrieved from config. files, for example).This code is from my project "HMI pybase" (see Projects).
Комментариев нет:
Отправить комментарий
Thanks for your posting!