简化小代码examp

2024-04-25 06:11:11 发布

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

假设我有下面的代码。在

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?在


Tags: 代码in列表forifitemonethree
3条回答

当然,您可以使用字典来查找答案:

lst = ['one', 'two', 'three']
resp = { 'one': num1, 'two': num2, 'three': num3 }

for item in lst:
  print resp[item]

不过,这还是相当静态的。另一种方法是面向对象,因此您可以在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

相关问题 更多 >