简化小代码示例

Orj*_*anp 0 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
Run Code Online (Sandbox Code Playgroud)

当列表和打印句子之间没有相关性时,有没有办法使这更优雅?意思是,有没有办法摆脱ifs和elifs?

unw*_*ind 5

您当然可以使用字典来查找响应:

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

for item in lst:
  print resp[item]
Run Code Online (Sandbox Code Playgroud)

不过,这仍然是非常静态的.另一种方法是面向对象,因此您可以在对象中实现一个函数lst来做出决策.


Sil*_*ost 5

>>> tups = ('one', 33), ('two', 45), ('three', 76)
>>> for i, j in tups:
    print(j)


33
45
76
Run Code Online (Sandbox Code Playgroud)