2024-04-25 06:11:11 发布
网友
假设我有下面的代码。在
num1 = 33 num2 = 45 num3 = 76 lst = ['one', 'two', 'three'] for item in lst: if item == 'one': print num1 elif item == 'two': print num2 elif item == 'three': print num3
当列表和打印句子之间没有关联时,有没有一种方法可以使它更优雅?意思是,有没有办法摆脱ifs和elifs?在
当然,您可以使用字典来查找答案:
lst = ['one', 'two', 'three'] resp = { 'one': num1, 'two': num2, 'three': num3 } for item in lst: print resp[item]
不过,这还是相当静态的。另一种方法是面向对象,因此您可以在lst中的对象中实现一个函数来做出决定。在
lst
您的代码是否有意忽略任何if/elif子句中未提及的对象?如果是这样,如果找不到对象,请使用默认值为“无”的字典:
lst = ['one', 'two', 'three'] d = { 'one': 33, 'two': 45, 'three': 76} for item in lst: x = d.get(item) if x is not None: print x
>>> tups = ('one', 33), ('two', 45), ('three', 76) >>> for i, j in tups: print(j) 33 45 76
当然,您可以使用字典来查找答案:
不过,这还是相当静态的。另一种方法是面向对象,因此您可以在
lst
中的对象中实现一个函数来做出决定。在您的代码是否有意忽略任何if/elif子句中未提及的对象?如果是这样,如果找不到对象,请使用默认值为“无”的字典:
相关问题 更多 >
编程相关推荐