简化小代码示例

时间:2009-12-11 12:14:35

标签: 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?

7 个答案:

答案 0 :(得分:5)

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

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

for item in lst:
  print resp[item]

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

答案 1 :(得分:5)

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


33
45
76

答案 2 :(得分:4)

您的代码是否故意忽略任何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

答案 3 :(得分:2)

if / else的整个逻辑等同于字典的键和值对

d = {"one":33, "two":44, "three":76}

您的代码的这一部分

if item == 'one':
    print num1

相同
print d["one"]

对其他人来说是明智的

答案 4 :(得分:1)

如果你有这样的字典:

d = {"one":33, "two":44, "three":76}

您可以这样打印:

for k in d.keys():
    print d[k]

这假设您不关心订单。

答案 5 :(得分:1)

对于您的简单示例,在其他答案中弹出的直接查找是最好的。但有时您需要为每个条件运行完全不同的代码,因此以下习惯用法也可能有用:

class MyClass(object):

    def process(self, item):
        # Select the method to call based on item value
        return getattr(self, 'do_'+item)()

    def do_one(self):
        # do something here

    def do_two(self):
        # do something other here

    # ... other methods ...

答案 6 :(得分:1)

如果if子句和打印件之间没有关联,则可以创建映射字典来存储关联。您需要小心映射到numx的变量,而不是当前值(因此使用eval函数):

num1 = 33
num2 = 45
num3 = 76
lst = ['one', 'two', 'three']

map = {'one': 'num1', 'two': 'num2', 'three': 'num3'} 

for item in lst:
    print item in map and eval(map[item]) or 'Unknown'

如果您确定该项目在地图中,则最后一行可以进一步简化为:

    print eval(map[item])
相关问题