是否有比这一种更多的节奏式方法来执行嵌套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-21 23:10:20
虽然@Aryerez和@SencerH.的答案有效,但在列出值对时,必须为numeral_sys_2的每个可能值反复写入每个可能的值,从而使数据结构在可能值的数量增加时更难维护。相反,可以使用嵌套的dict代替嵌套的if语句:
mapping = {
'Hexadecimal': {'Decimal': 1, 'Binary': 2},
'Binary': {'Decimal': 3, 'Hexadecimal': 5},
'Decimal': {'Hexadecimal': 4, 'Binary': 6}
}
def convert_what(numeral_sys_1, numeral_sys_2):
return mapping.get(numeral_sys_1, {}).get(numeral_sys_2, 0)或者,您可以使用itertools.permutations方法生成映射的值对,其顺序与输入序列的顺序相同:
mapping = dict(zip(permutations(('Hexadecimal', 'Decimal', 'Binary'), r=2), (1, 2, 4, 6, 3, 5)))
def convert_what(numeral_sys_1, numeral_sys_2):
return mapping.get((numeral_sys_1, numeral_sys_2), 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)如果您计划在循环中使用函数,那么最好在函数外部定义字典,这样就不会在每次调用该函数时重新创建它。
发布于 2019-11-21 12:07:10
如果您确信没有其他值可以设置为numeral_sys_1和numeral_sys_2变量,那么这是最简单和最干净的解决方案。
另一方面,如果您有“十六进制”、“十进制”和“二进制”以外的任何其他值,则必须扩展字典及其与可用值的组合。
这里的逻辑是;如果字典键中的变量元组不等于给定的变量元组,则.get()方法返回"0“。如果给定变量元组匹配字典中的任何键,则返回匹配键的值。
def convert_what(numeral_sys_1, numeral_sys_2):
return {
("Hexadecimal", "Decimal") : 1,
("Hexadecimal", "Binary") : 2,
("Binary", "Decimal") : 3,
("Decimal", "Hexadecimal") : 4,
("Binary", "Hexadecimal") : 5,
("Decimal", "Binary") : 6,
}.get((numeral_sys_1, numeral_sys_2), 0)也有使用生成器的可能解决方案。看起来要聪明得多,但我认为硬编码字典比使用生成器来满足这一简单要求更快。
https://stackoverflow.com/questions/58927718
复制相似问题