所以我试图为我的python脚本创建一个case语句以使它更干净但是没有这样的东西(据我所知)所以我刚刚制作了一堆if / else语句。有没有办法让这个更干净?
if (config.dutCardTypes[0] in [6, 7]) and (config.isPrimary) and (config.measPwr): ### Power Measurement for 28nm on Primary Only
if dsppif[dutDevId].pifReadData(0x1e800) == 0x1 :
print "Link Up, Measuring SteadyState Power..."
if (("Sahara Validation" in dsppif[dutDevId].board.description)) :
v, i, pwr = getOnBoardPwr(dsppif[dutDevId],"Sahara Validation")
vdd21A_pwr = pwr["P2V1"]
vdd12A_pwr = pwr["P1V2"]
vdd_pwr = pwr["VDD"]
vdd3v3_pwr = pwr["P3V3"]
elif "Athena" in dsppif[dutDevId].board.description:
if (("Quad A" in dsppif[dutDevId].board.description)) :
v, i, pwr = getOnBoardPwr(dsppif[dutDevId],"Athena Quad A")
vdd21A_pwr = pwr["P2V1_A"] + pwr["P2V1_B"] + pwr["P2V1_C"] + pwr["P2V1_D"] + pwr["P2V1_E"]
vdd12A_pwr = pwr["P1V2_A"] + pwr["P1V2_B"]
vdd_pwr = pwr["VDD"]
elif (("Quad B" in dsppif[dutDevId].board.description)) :
v, i, pwr = getOnBoardPwr(dsppif[dutDevId],"Athena Quad B")
vdd21A_pwr = pwr["P2V1_A"] + pwr["P2V1_B"] + pwr["P2V1_C"] + pwr["P2V1_D"] + pwr["P2V1_E"]
vdd12A_pwr = pwr["P1V2_A"] + pwr["P1V2_B"]
vdd_pwr = pwr["VDD"]
elif (("Quad C" in dsppif[dutDevId].board.description)) :
v, i, pwr = getOnBoardPwr(dsppif[dutDevId],"Athena Quad C")
vdd21A_pwr = pwr["P2V1_A"] + pwr["P2V1_E"]
vdd12A_pwr = pwr["P1V2_A"]
vdd_pwr = pwr["VDD"]
答案 0 :(得分:3)
在高层次上,python建议你尝试使用词典来做这种事情。 我不会尝试翻译你的例子,因为它有点冗长,但实际上并没有使用像这样的案例陈述:
function(argument){
switch(argument) {
case 0:
return "zero";
case 1:
return "one";
case 2:
return "two";
default:
return "nothing";
};
};
你可以使用像这样的可能性词典
def numbers_to_strings(argument):
switcher = {
0: "zero",
1: "one",
2: "two",
}
return switcher.get(argument, "nothing")
您还可以创建切换器类,并将您的操作映射到您的条件。总的来说,python方式是提高易读性。