for index1, itme1 in enumerate(list_col): for index, itme in enumerate(list_row): if itme1 == '总计': count = count_conditions( teacher_arr, lambda row: row[9] == '学前' or row[9] == '小学', lambda row: row[8] == itme) if count != 0: sh_4149.cell(index1+6, index+4).value = count if itme1 == '女': count = count_conditions( teacher_arr, lambda row: row[2] == '女', lambda row: row[8] == itme) if count != 0: sh_4149.cell(index1+6, index+4).value = count if itme1 == '少数民族': count = count_conditions( teacher_arr, lambda row: row[11] != '汉族', lambda row: row[8] == itme) if count != 0: sh_4149.cell(index1+6, index+4).value = count if itme1 == '在编人员': count = count_conditions( teacher_arr, lambda row: row[12] == '是', lambda row: row[8] == itme) if count != 0: sh_4149.cell(index1+6, index+4).value = count代码优化
时间: 2023-06-09 17:07:27 浏览: 78
charts:由Itme发布的Helm图表(主要与Solid相关)
有很多地方可以优化这段代码,以下是几点建议:
1.可以将重复的代码提取出来生成一个函数,减少冗余代码。
2.对于多个if语句,可以使用字典来存储对应的条件和函数,并用一个循环来执行它们。
3.可以使用列表解析式来统计数量,这样可以减少不必要的循环和判断。
4.可以使用zip函数来同时遍历两个列表,简化代码。
5.可以使用at函数来直接赋值,避免使用cell函数。
优化后的代码如下:
def count_conditions(teacher_arr, *conditions):
return sum(1 for row in teacher_arr if all(c(row) for c in conditions))
def find_count(teacher_arr, sheet):
row_names = [cell.value for cell in sheet[1, 1:]]
col_names = [cell.value for cell in sheet[2:, 0]]
conditions = {
'总计': (lambda row: row[9] in ('学前', '小学')),
'女': (lambda row: row[2] == '女'),
'少数民族': (lambda row: row[11] != '汉族'),
'在编人员': (lambda row: row[12] == '是')
}
for col_idx, col_name in enumerate(col_names):
for row_idx, row_name in enumerate(row_names):
if row_name in conditions and col_name != '':
count = count_conditions(teacher_arr, conditions[row_name], lambda row: row[8] == col_name)
if count != 0:
sheet[row_idx+1, col_idx+1] = count
# 使用样例
teacher_arr = [...]
sh_4149 = [...]
find_count(teacher_arr, sh_4149)
阅读全文