我的脚本运行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()
循环中的大部分逻辑可以使用生成器表达式编写,这是等效的代码,并考虑了@DSM在注释中的建议:
不幸的是,Python无法做到这一点。如果你使用C++,你可以使用开关语句,但是Python没有这样的均衡。对不起的!在
使用字典将传感器ID映射到人类可读名称:
这种方法的优点是,
get
方法将在没有人为可读名称的情况下返回ID而不做任何更改。在相关问题 更多 >
编程相关推荐