我能用听写法吗,还是有更好的方法?

2024-04-28 15:30:39 发布

您现在位置:Python中文网/ 问答频道 /正文

我能用听写法吗,还是有更好的方法?你知道吗

if data_msb=='1' or data_lsb=='1' or addr_msb=='1' or addr_lsb=='1':
     print_hex_vector(hexF,hex1,modify_vector,output_file,line)
if data_msb=='2' or data_lsb=='2' or addr_msb=='2' or addr_lsb=='2':
     print_hex_vector(hexF,hex2,modify_vector,output_file,line)   
if data_msb=='3' or data_lsb=='3' or addr_msb=='3' or addr_lsb=='3':
     print_hex_vector(hexF,hex3,modify_vector,output_file,line)
if data_msb=='4' or data_lsb=='4' or addr_msb=='4' or addr_lsb=='4':
     print_hex_vector(hexF,hex4,modify_vector,output_file,line)
if data_msb=='5' or data_lsb=='5' or addr_msb=='5' or addr_lsb=='5':
     print_hex_vector(hexF,hex5,modify_vector,output_file,line)
if data_msb=='6' or data_lsb=='6' or addr_msb=='6' or addr_lsb=='6':
     print_hex_vector(hexF,hex6,modify_vector,output_file,line)

Tags: or方法outputdataiflinefileaddr
2条回答

就像迪杰斯特拉说的:

"Two or more, use a for" - Edsger W. Dijstra

这实际上是一个咒语反对复制粘贴和slightly修改代码。从你必须这样做的那一刻起,你就应该开始思考“我该如何概括这一点?”。你知道吗

如何使用:

setvals = {data_msb,data_lsb,addr_msb,addr_lsb}
for vl,hx in [('1',hex1),('2',hex2),('3',hex3),('4',hex4),('5',hex5),('6',hex6)]:
    if vl in setvals:
        print_hex_vector(hexF,hx,modify_vector,output_file,line)

如果值数字字符串'1''2'等,您可以使用:

setvals = {data_msb,data_lsb,addr_msb,addr_lsb}
for vl,hx in enumerate([hex1,hex2,hex3,hex4,hex5,hex6],1):
    if str(vl) in setvals:
        print_hex_vector(hexF,hx,modify_vector,output_file,line)

枚举中的1用于说明值以'1'开头。你知道吗

使用set将略微提高性能。因为现在查找将平均在O(1)中进行,因此可能减少检查的数量。你知道吗

为什么不把所有的hexN变量放在一个列表中并迭代呢?你知道吗

for i in range(len(hexes)):
    if str(i+1) in [data_msb, data_lsb, addr_msb, addr_lsb]:
        print_hex_vector(hexF, hex[i], modify_vector, output_file, line)

相关问题 更多 >