如何打印出员工的层次结构树

时间:2016-07-20 03:34:30

标签: python

将员工及其老板列表作为csv文件,编写一个打印出员工层次树的函数。

来自csv文件的示例输入

Sam, Ian, technical lead, 2009 / Ian, NULL, CEO,2007/ Fred, Sam,developer, 2010

格式是姓名,主管,指定,加入年份。

输出应为

Ian CEO 2007

-Sam Technical lead 2009

--Fred Developer 2010

我不确定,但我尝试过如下。请建议更改此代码或您拥有的任何其他解决方案。

strq = "Sam, Ian, technical lead, 2009 / Ian, NULL, CEO,2007/Fred, Sam, developer, 2010"
def treeEmployee(infoStr):
    str1 = infoStr.split("/")
    s2 = []
    for i in str1:
        s2.append(i.split(","))
    for i in range(len(s2)):
        for j in range(1, len(s2)):
            if s2[i][1] == s2[j][0]:
                s2[i], s2[j] = s2[j], s2[i]
            return s2

print treeEmployee(strq)

我希望输出为

Ian CEO 2007

-Sam Technical lead 2009

--Fred Developer 2010

2 个答案:

答案 0 :(得分:0)

修复这样的缩进应该有效。缩进在python中非常重要。

strq = "Sam, Ian, technical lead, 2009 / Ian, NULL, CEO,2007/Fred, Sam, developer, 2010"
def treeEmployee(infoStr):
    str1 = infoStr.split("/")
    s2 = []
    for i in str1:
        s2.append(i.split(","))
    for i in range(len(s2)):
        for j in range(1, len(s2)):
            if s2[i][1] == s2[j][0]:
                s2[i], s2[j] = s2[j], s2[i]
                return s2

答案 1 :(得分:0)

这将从JS中的输入生成层次结构树。



function wrapper(str) {
  var elem;
  str = str.split('/');

  function tree(parent, arr, level) {
    if (!parent) {
      parent = 'NULL';
    }
    if (!arr) {
      arr = [];
    }
    if (!level) {
      level = 0;
    }
    var obj,
      children = findChild(parent);

    for (var i = 0, len = children.length; i < len; i += 1) {
      elem = children[i];
      obj = {
        name: elem[0],
        supervisor: parent,
        designation: elem[2],
        yearOfJoining: elem[3],
        children: [],
        level: level
      };
      arr.push(obj);
      console.log(dashGenerator(level) + obj.name + ' ' + obj.designation + ' ' + obj.yearOfJoining);
      tree(elem[0], obj.children, level + 1);
    }
    return arr;
  }

  function dashGenerator(level) {
    var str = '';
    for (var i = 0; i < level; i += 1) {
      str += '-';
    }
    return str;
  }

  function findChild(parent) {
    var child = [];
    for (var i = 0, len = str.length; i < len; i += 1) {
      elem = str[i].split(',')
      if (elem[1].trim() === parent.trim()) {
        child.push(elem);
      }
    }
    return child;
  }
  tree();
}
wrapper("Sam, Ian, technical lead, 2009 / Ian, NULL, CEO,2007/ Fred, Sam,developer, 2010");
&#13;
&#13;
&#13;