很抱歉,我问了一个基本的问题,但我一直在做一个信号分析项目,我们需要为这个项目分配一个变量,一个象限的值集(n维向量)位于哪个象限中。作为一名生物医学工程师,我一直在努力寻找更有效或更“漂亮”的解决方案。目前,我为三维向量工作的方式是做多个比较:
if (ondas[0]>0)&(ondas[1]>0)&(ondas[2]>0):
note=1
elif (ondas[0]>0)&(ondas[1]>0)&(ondas[2]<0):
note=2
elif (ondas[0]>0)&(ondas[1]<0)&(ondas[2]<0):
note=3
elif (ondas[0]<0)&(ondas[1]<0)&(ondas[2]<0):
note=4
elif (ondas[0]<0)&(ondas[1]>0)&(ondas[2]<0):
note=5
elif (ondas[0]<0)&(ondas[1]<0)&(ondas[2]>0):
note=6
elif (ondas[0]<0)&(ondas[1]>0)&(ondas[2]>0):
note=7
elif (ondas[0]>0)&(ondas[1]<0)&(ondas[2]>0):
note=8
else:
note=0其中ondas是我的数组,有3个值。这段代码运行得很好,但我想知道是否还有其他方法来解决这个问题。我在这个解决方案上已经做得够好了,但我愿意听取关于这个问题的反馈意见。
发布于 2022-09-23 20:36:39
有许多不同的方法来处理这个问题。最简单的方法可能是为每个轴创建一个布尔值,并将每个配置的象限存储在字典中。这与你所做的基本相同,只是更短、更清晰:
axis_to_quad = {(0, 0, 0): 1,
(0, 0, 1): 2,
(0, 1, 1): 3,
(1, 1, 1): 4,
(1, 0, 1): 5,
(1, 1, 0): 6,
(1, 0, 0): 7,
(0, 1, 0): 8}
note = axis_to_quad[(ondas[0] < 0, ondas[1] < 0, ondas[2] < 0)]发布于 2022-09-23 20:53:44
没有真正改变您的逻辑,而是用&替换为and,去掉了大量的父类,添加了一些空格,并使用了一个条件表达式。
note = 1 if ondas[0] > 0 and ondas[1] > 0 and ondas[2] > 0 else \
2 if ondas[0] > 0 and ondas[1] > 0 and ondas[2] < 0 else \
3 if ondas[0] > 0 and ondas[1] < 0 and ondas[2] < 0 else \
4 if ondas[0] < 0 and ondas[1] < 0 and ondas[2] < 0 else \
5 if ondas[0] < 0 and ondas[1] > 0 and ondas[2] < 0 else \
6 if ondas[0] < 0 and ondas[1] < 0 and ondas[2] > 0 else \
7 if ondas[0] < 0 and ondas[1] > 0 and ondas[2] > 0 else \
8 if ondas[0] > 0 and ondas[1] < 0 and ondas[2] > 0 else \
9 https://stackoverflow.com/questions/73832661
复制相似问题