如何减少elif语句

2024-10-04 03:16:10 发布

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

我的脚本运行C程序digitemp。输出以行为单位,包含传感器ID和温度。我需要将传感器ID与一个特定的名称匹配,因此所有的ELIF。在这个例子中,我使用了first,second-third作为ID的数学名称,有什么方法可以减少所有的elif语句,因为还有更多要添加的语句?在

import os

# get digitemps output
cmd = "/bin/digitemp_ -c /bin/digitemp.conf -q -a"

def digitemps():
    for outline in os.popen(cmd).readlines():
        outline = outline[:-1].split()
        if outline[0] == '28F4F525030000D1':
            temp_ = outline[1]
            print 'first ' + temp_
        elif outline[0] == '28622A260300006B':
            temp_ = outline[1]
            print 'second ' + temp_
        elif outline[0] == '28622A2603000080':
            temp_ = outline[1]
            print 'third ' + temp_

digitemps()

Tags: 名称cmdidos传感器语句tempfirst
3条回答

循环中的大部分逻辑可以使用生成器表达式编写,这是等效的代码,并考虑了@DSM在注释中的建议:

d = {'28F4F525030000D1':'first ',
     '28622A260300006B':'second ',
     '28622A2603000080':'third '}

def digitemps():
  for s in (d.get(x[0],x[0]) + x[1] for x in (e.split() for e in os.popen(cmd))):
    print s

不幸的是,Python无法做到这一点。如果你使用C++,你可以使用开关语句,但是Python没有这样的均衡。对不起的!在

使用字典将传感器ID映射到人类可读名称:

id_to_name = {"28F4F525030000D1": "first",
              "28622A260300006B": "second",
              "28622A2603000080", "third"}
print id_to_name.get(outline[0], outline[0]) + outline[1]

这种方法的优点是,get方法将在没有人为可读名称的情况下返回ID而不做任何更改。在

相关问题 更多 >