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

时间:2016-02-19 21:14:16

标签: python-2.7 code-duplication

我是一名学生,他习惯于在整个地方复制代码,这是我想要改变的。

下面,我从我正在编写的函数中获得了一段代码。快速解释:代码会查看人员的人力资源网站,并返回有关他管理的员工的信息(假设他管理任何人)。

有两种类型的员工:普通员工和合同工。在网站上,经理下面的常规员工都将列在employeeList下,承包商将列在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并获取值而不复制代码?

(因为我是一名相对初学者,所以您可以提供的任何简单示例都会非常感激)

3 个答案:

答案 0 :(得分:2)

对于初学者来说,每次看到重复的内容时,请考虑创建一个可变的前端&用那个。之后,您可以决定应该将哪些因素纳入函数中。下面,我刚删除了大部分重复的项目。

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)

答案 1 :(得分:1)

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

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')

答案 2 :(得分:0)

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

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)