3

我的脚本运行 C 程序 digitemp。输出在包含传感器 ID 和温度的行中。我需要将传感器 ID 与特定名称匹配,因此所有 elifs。在此示例中,我使用了第一、第二、第三作为名称来计算 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()
4

3 回答 3

4

Use a dictionary to map from sensor ID to a human-readable name:

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

The advantage of this approach is that the get method will return the ID without any change if there is no human-readable name assigned to it.

于 2013-04-14T19:46:08.187 回答
0

循环内的大部分逻辑都可以使用生成器表达式编写,这是等效的代码,并考虑了@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
于 2013-04-14T19:56:06.647 回答
-2

Unfortunately, Python has no way of doing so. If you were using C++, you could've used the switch statement, but Python has no such equilavent. Sorry!

于 2013-04-14T19:47:39.500 回答