20201019_02_简化代码
Posted azxsdcv
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了20201019_02_简化代码相关的知识,希望对你有一定的参考价值。
案例:请简化以下代码
m = 0
for i in range(3,length_a1):
# 从设备侧文档 判断层级,验证层级,并打印层级关系
if table1.col(1)[i].value == ‘‘:
print(table1.col(3)[i].value + ":第一层")
m += 1
worksheet1.write(m,0,table1.col(3)[i].value)
worksheet1.write(m,1,‘第 1 层‘)
worksheet1.write(m,2,‘【‘ + table1.col(3)[i].value + ‘】‘ + ‘是顶层!‘)
if table1.col(2)[i].value in F_Mo:
# print(table1.col(3)[i].value + ":第一层 存在 子MO")
for i01 in range(3,length_a1):
if table1.col(2)[i].value == table1.col(1)[i01].value:
print(table1.col(3)[i01].value + ":第二层 " + "上一层级为:" + table1.col(3)[i].value)
m += 1
worksheet1.write(m,0,table1.col(3)[i01].value)
worksheet1.write(m,1,‘第 2 层‘)
worksheet1.write(m,2,table1.col(3)[i].value)
if table1.col(2)[i01].value in F_Mo:
# print(table1.col(3)[i01].value + ":第二层 存在 子MO")
for i02 in range(3,length_a1):
if table1.col(2)[i01].value == table1.col(1)[i02].value:
print(table1.col(3)[i02].value + ":第三层" + "上一层级为:" + table1.col(3)[i01].value)
m += 1
worksheet1.write(m,0,table1.col(3)[i02].value)
worksheet1.write(m,1,‘第 3 层‘)
worksheet1.write(m,2,table1.col(3)[i01].value)
if table1.col(2)[i02].value in F_Mo:
#print(table1.col(3)[i02].value + ":第三层 存在 子MO")
for i03 in range(3,length_a1):
if table1.col(2)[i02].value == table1.col(1)[i03].value:
print(table1.col(3)[i03].value + ":第四层" + "上一层级为:" + table1.col(3)[i02].value)
m += 1
worksheet1.write(m,0,table1.col(3)[i03].value)
worksheet1.write(m,1,‘第 4 层‘)
worksheet1.write(m,2,table1.col(3)[i02].value)
.......如果有 几十层 怎么办?
方案1:
data = {}
for i in range(3,length_a1):
parent, name, zh = table1.col(1)[i].value, table1.col(2)[i].value, table1.col(3)[i].value
data[name] = {‘parent‘: parent, ‘name‘: name, ‘zh‘: zh, ‘level‘: 0}
while True:
mod = False
for v in data.values():
if v[‘level‘] == 0:
if v[‘parent‘] == ‘‘:
v[‘level‘] = 1
mod = True
elif data[v[‘parent‘]][‘level‘] != 0:
v[‘level‘] = data[v[‘parent‘]][‘level‘] + 1
mod = True
if not mod: break
print(data)
m = 0
for v in data.values():
m += 1
worksheet1.write(m, 0, v[‘zh‘])
worksheet1.write(m, 1, ‘第 {} 层‘.format(v[‘level‘]))
if v[‘level‘] == 1:
worksheet1.write(m, 2, ‘【{}】是顶层!‘.format(v[‘zh‘]))
else:
worksheet1.write(m, 2, ‘{}‘.format(data[v[‘parent‘]][‘zh‘]))
以上是关于20201019_02_简化代码的主要内容,如果未能解决你的问题,请参考以下文章