如何减少 Python 中 If-Else 语句的代码重复

How to Reduce Code Duplication of If-Else Statements in Python

我是一名学生,有一个非常坏的习惯,就是到处复制代码,这是我想改变的。

下面是我正在编写的函数中的一段代码。快速解释:该代码会查看一个人的人力资源网站,以及 return 关于他管理的员工的信息(假设他管理任何人)。

有两种类型的员工:正式员工和合同工。在网站上,manager手下的正式员工都会列在employeeList下,contractor会列在contractWorkerList下。

response = opener.open('myFakeOrgHierarchy.com/JohnSmith_The_Manager')
allDataFromPage = (response.read())
jsonVersionOfAllData = json.loads(allDataFromPage)

listOfAllReports = []

numOfEmployeeDirectReports = len(jsonVersionOfAllData['employeeList']['list'])
numOfContractWorkerReports = len(jsonVersionOfAllData['contractWorkerList']['list'])

if numOfEmployeeDirectReports != 0:
    for i in range(0, numOfEmployeeDirectReports, 1):
        workerInfo = {}
        workerInfo['empLname'] = jsonVersionOfAllData['employeeList']['list'][i]['lastName']
        workerInfo['empFname'] = jsonVersionOfAllData['employeeList']['list'][i]['firstName']
        listOfAllReports.append(workerInfo)

if numOfContractWorkerReports != 0:
    for i in range(0, numOfContractWorkerReports, 1):
        workerInfo = {}
        workerInfo['empLname'] = jsonVersionOfAllData['contractWorkerList']['list'][i]['lastName']
        workerInfo['empFname'] = jsonVersionOfAllData['contractWorkerList']['list'][i]['firstName']
        listOfAllReports.append(workerInfo)

如您所见,我有几行代码与其他行几乎相同,只有很小的变化。有没有一种方法可以同时检查 contractWorkerList 和 employeeList 以查看它们是否不为空,并且(假设它们不为空)遍历 contractWorkerList 和 employeeList 并在不重复代码的情况下获取值?

(由于我是一个相对初学者,如果您能在推荐中提供任何简单的示例,我们将不胜感激)

避免代码重复的最常见方法是使用该代码定义一个函数。

def checkIfEmpty(numOfReports, listName):
    if numOfReports != 0:
        for i in range(0, numOfReports, 1):
            workerInfo = {}
            workerInfo['empLname'] = jsonVersionOfAllData[listName]['list'][i]['lastName']
            workerInfo['empFname'] = jsonVersionOfAllData[listName]['list'][i]['firstName']
            listOfAllReports.append(workerInfo)

所以你最终会得到简单易读的代码:

checkIfEmpty(numOfEmployeeDirectReports, 'employeeList')
checkIfEmpty(numOfContractWorkerReports, 'contractWorkerList')

在这种特殊情况下,您可以这样做:

for var, key in [(numOfEmployeeDirectReports, 'employeeList'),
                 (numOfContractWorkerReports, 'contractWorkerList')]:
    if var != 0:
        for i in range(0, var, 1):
            workerInfo = {}
            workerInfo['empLname'] = jsonVersionOfAllData[key]['list'][i]['lastName']
            workerInfo['empFname'] = jsonVersionOfAllData[key]['list'][i]['firstName']
            listOfAllReports.append(workerInfo)

对于初学者来说,每当您看到重复的内容时,请考虑预先创建一个变量并使用它。之后,您可以决定应该将什么分解为一个函数。下面,我只是删除了大部分重复的项目。

response = opener.open('myFakeOrgHierarchy.com/JohnSmith_The_Manager')
allDataFromPage = (response.read())
jsonVersionOfAllData = json.loads(allDataFromPage)

listOfAllReports = []

for listType in ('employeeList', 'contractWorkerList'):

    json_ver = jsonVersionOfAllData[listType]['list']
    directReports = len(json_ver)

    if directReports != 0:
        for i in range(0, directReports, 1):
            workerInfo = {}
            for wi_name, json_name in (('empLname', 'lastName'), ('empFname', 'firstName')):
                workerInfo[wi_name] = json_ver[i][json_name]
            listOfAllReports.append(workerInfo)