这个问题根本不同于所提到的可能重复的问题。这是关于清理一个长条件的并寻找一种更优雅的表达方式。
这段代码很难看,不是pythonic。我是python的新手,不是编程的新手。不用猜测许多可能的伪装之一,您能告诉我执行此操作的pythonic方法吗?
如您所见,一堆变量(向前,向左,向右等)设置了浮点数。我想在变量“ closest_dir”中存储包含最小值的变量的字符串名称。
forward = calc_range(msg.ranges, 359, 0, 15)
right = calc_range(msg.ranges, 270, 271, 15)
left = calc_range(msg.ranges, 90, 91, 15)
back = calc_range(msg.ranges, 180, 181, 15)
narrow_l1 = sum(msg.ranges[83:87])/5
narrow_l2 = sum(msg.ranges[88:92])/5
narrow_l3 = sum(msg.ranges[93:97])/5
narrow_r1 = sum(msg.ranges[273:277])/5
narrow_r2 = sum(msg.ranges[268:272])/5
narrow_r3 = sum(msg.ranges[263:267])/5
closest_dist = min(narrow_l1, narrow_l2, narrow_l3, narrow_r1, narrow_r2, narrow_r3,
forward, left, right, back)
if (closest_dist == forward):
closest_dir = "forward"
elif (closest_dist == left):
closest_dir = "left"
elif (closest_dist == right):
closest_dir = "right"
elif (closest_dist == back):
closest_dir = "back"
elif (closest_dist == narrow_l1):
closest_dir = "narrow_l1"
elif (closest_dist == narrow_l2):
closest_dir = "narrow_l2"
elif (closest_dist == narrow_l3):
closest_dir = "narrow_l3"
elif (closest_dist == narrow_r1):
closest_dir = "narrow_r1"
elif (closest_dist == narrow_r2):
closest_dir = "narrow_r2"
elif (closest_dist == narrow_r3):
closest_dir = "narrow_r3"
else:
closest_dir = "bug"
答案 0 :(得分:5)
使用字典。
foos = {
'forward': calc_range(msg.ranges, 359, 0, 15),
'right': calc_range(msg.ranges, 270, 271, 15),
'left': calc_range(msg.ranges, 90, 91, 15),
'back': calc_range(msg.ranges, 180, 181, 15),
'narrow_l1': sum(msg.ranges[83:87]/5),
'narrow_l2': sum(msg.ranges[88:92])/5,
'narrow_l3': sum(msg.ranges[93:97])/5,
'narrow_r1': sum(msg.ranges[273:277])/5,
'narrow_r2': sum(msg.ranges[268:272])/5,
'narrow_r3': sum(msg.ranges[263:267])/5,
}
closest_dir = min(foos, key=foos.get)
min
使用dict
迭代器,该迭代器返回密钥,并且key
自变量表示foo.get(x)
将确定每个密钥{{1}的大小” }进行比较。