s = ['2-3-1-*-*','2-3-*-*-*','2-1-*-*-*','1-4-3-*-*','2-3-2-*-*','2-1-3-*-*','1-1-*-*-*','2-3-1-1-*']
def isSubElement(subelement, element):
return (subelement != element) and all([(e1 == e2) or (e1 == "*" and e2 != "*") for e1, e2 in zip(element.split('-'), subelement.split('-'))])
def parseTree(elementList):
if len(elementList) == 0:
return {}
elements = elementList[:]
d = {}
for element1 in elements:
parent = True
for element2 in elements:
if isSubElement(element1, element2):
parent = False
break
if parent:
d[element1] = {}
for element1 in d.keys():
d[element1] = parseTree([element for element in elements if isSubElement(element, element1)])
return d
print parseTree(s)
输出:
{'2-1-*-*-*':
{'2-1-3-*-*':
{}},
'1-4-3-*-*':
{},
'1-1-*-*-*':
{},
'2-3-*-*-*':
{'2-3-1-*-*':
{'2-3-1-1-*':
{}},
'2-3-2-*-*':
{}}}