Python员工层次结构递归函数错误:#构造一个有序的字典以存储结果

时间:2020-08-26 08:41:13

标签: python pandas list

df

Employee Id    Manager ID
1                3
2                1
3                4
4                NULL
5                NULL
6                7
7                5  and so on

因此,4和5个emp id是CXO。继承制的预期输出:(经理在他之下的雇员)

1 -> 2
2 -> None
3 -> 1,2
4 -> 3,1,2
5 -> 7,6
6 -> None
7 -> 6

例如4是3(级别1)的管理者,3是1(级别2)的管理者,1是2(级别3)的管理者。

为创建员工经理词典而编写的代码:(根据下面的输入进行了一些更改)

#convert pandas to list for employee to manager mapping    
list22=df.set_index('Employee Id').T.to_dict('list')    

查找员工层次结构的代码:(效果很好)

# Recursive DP function to find all employees who directly or indirectly
# reports to a given manager and store the result in the result dict
def findAllReportingEmployees(manager, managerToEmployeeMappings, result):

# if the sub-problem is already seen before
    if manager in result:
        # return the already computed mapping
        return result.get(manager)

    # find all employees reporting directly to the current manager
    managerEmployees = managerToEmployeeMappings.get(manager)

    if managerEmployees:
        # find all employees reporting in-directly to the current manager
        for reportee in managerEmployees.copy():
            # find all employees reporting to the current employee
            employees = findAllReportingEmployees(reportee, managerToEmployeeMappings,
                                                result)

            # move those employees to the current manager
            if employees:
                managerEmployees.extend(employees)

    # save the result to avoid re-computation and return it
    result[manager] = managerEmployees
    return managerEmployees


# Find all employees who directly or indirectly reports to a manager
def findEmployees(employeeToManagerMappings):

    # store manager to employee mappings in a dict
    # is used since a manager can have several employees mapped
    managerToEmployeeMappings = {}

    # fill above dict with the manager to employee mappings
    for employee, manager in employeeToManagerMappings.items():
        # don't map an employee with itself
        if employee != manager:
            managerToEmployeeMappings.setdefault(manager, []).append(employee)

    # construct an ordered dict to store the result
    result = {}

    # find all reporting employees (direct and indirect) for every manager
    # and store the result in a dict
    for key in employeeToManagerMappings.keys():
        findAllReportingEmployees(key, managerToEmployeeMappings, result)

    # print contents of the result dict
    for key, value in result.items():
        print(key, "->", value)

上述功能可以完美运行

问题代码:

if __name__ == '__main__':

    # construct a dictionary of employee to manager mappings
    employeeToManagerMappings = list22  #error here
    findEmployees(employeeToManagerMappings)

>**Error:**
>TypeError                                 Traceback (most recent call last)
<ipython-input-27-b35721965687> in <module>
     57         # construct a dictionary of employee to manager mappings
     58         employeeToManagerMappings = list22
---> 59         findEmployees(employeeToManagerMappings)

<ipython-input-27-b35721965687> in findEmployees(employeeToManagerMappings)
     38                 # don't map an employee with itself
     39                 if employee != manager:
---> 40                         managerToEmployeeMappings.setdefault(manager, []).append(employee)
     41 
     42         # construct an ordered dict to store the result

TypeError: unhashable type: 'list'

如果我在代码中使用伪数据并用下面的内容替换最后4行,则效果很好

if __name__ == '__main__':

    # construct a dictionary of employee to manager mappings
    employeeToManagerMappings = {'A': 'A', 'B': 'A', 'C': 'B',
                                'D': 'B', 'E': 'D', 'F': 'E'}
    findEmployees(employeeToManagerMappings)

在转换为列表后尝试在pandas数据帧上运行该函数时,会出现主要问题。

1 个答案:

答案 0 :(得分:0)

问题是您要分配内置类型

list

到您的变量

检查一下自己

type([1,2,3,4])

您需要为变量分配一些列表,最好不要遮盖内置类型(例如list),然后使用该变量作为参数来调用函数。