是否有比这一种更多的节奏式方法来执行嵌套if there语句:
def convert_what(numeral_sys_1, numeral_sys_2):
if numeral_sys_1 == numeral_sys_2:
return 0
elif numeral_sys_1 == "Hexadecimal":
if numeral_sys_2 == "Decimal":
return 1
elif numeral_sys_2 == "Binary":
return 2
elif numeral_sys_1 == "Decimal":
if numeral_sys_2 == "Hexadecimal":
return 4
elif numeral_sys_2 == "Binary":
return 6
elif numeral_sys_1 == "Binary":
if numeral_sys_2 == "Hexadecimal":
return 5
elif numeral_sys_2 == "Decimal":
return 3
else:
return 0此脚本是简单转换器的一部分。
发布于 2019-11-19 06:23:10
将所有有效组合插入到dictionary of tuples中,如果组合不存在,则返回0:
def convert_what(numeral_sys_1, numeral_sys_2):
numeral_dict = {
("Hexadecimal", "Decimal" ) : 1,
("Hexadecimal", "Binary" ) : 2,
("Decimal", "Hexadecimal") : 4,
("Decimal", "Binary" ) : 6,
("Binary", "Hexadecimal") : 5,
("Binary", "Decimal" ) : 3
}
return numeral_dict.get((numeral_sys_1, numeral_sys_2), 0)如果您计划在循环中使用函数,那么最好在函数外部定义字典,这样就不会在每次调用该函数时重新创建它。
https://stackoverflow.com/questions/58927718
复制相似问题