如何在python中对列表进行分组?

时间:2013-10-21 02:38:33

标签: python list tree

这里我得到了一个字符串列表:

['2-3-1-*-*','2-3-*-*-*','2-1-*-*-*','1-4-3-*-*','2-3-2-*-*','2-1-3-*-*','1-1-*-*-*','2-3-1-1-*'];

我正在尝试将此字符串分组为这样的结构:

--'2-3-*-*-*' 
   --'2-3-1-*-*'
      --'2-3-1-1-*'
   --'2-3-2-*-*'
--'2-1-*-*-*'
   --'2-1-3-*-*'
--'1-4-3-*-*'
--'1-1-*-*-*'

这就像树形结构。我是编程的初学者,所以有人可以给我一个暗示我如何构建树状结构和我可以使用的任何合适的结构?

2 个答案:

答案 0 :(得分:1)

如果您使用某些js库来呈现它,请将其另存为嵌套dict,以便可以毫不费力地将其导出为JSON。

def parser(items):
    nested_dicts = {}

    for item in items:
        nodes = item.split('-')
        current_dict = nested_dicts
        for n in nodes[:-1]:
            current_dict = current_dict.setdefault(n, {})

        last = nodes[-1]
        current_dict[last] = current_dict.get(last, 0) + 1

    return nested_dicts

提供数据的示例输出:

{
  "1": {
    "1": {
      "*": {
        "*": {
          "*": 1
        }
      }
    }, 
    "4": {
      "3": {
        "*": {
          "*": 1
        }
      }
    }
  }, 
  "2": {
    "1": {
      "3": {
        "*": {
          "*": 1
        }
      }, 
      "*": {
        "*": {
          "*": 1
        }
      }
    }, 
    "3": {
      "1": {
        "1": {
          "*": 1
        }, 
        "*": {
          "*": 1
        }
      }, 
      "2": {
        "*": {
          "*": 1
        }
      }, 
      "*": {
        "*": {
          "*": 1
        }
      }
    }
  }
}

答案 1 :(得分:1)

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-*-*': 
        {}}}