【发布时间】:2022-01-23 06:39:52
【问题描述】:
我有四个自定义Trial 对象列表,其中包含有关实验中各个试验的数据。这些列表是MC_inducer_con、MC_inducer_diamond_con、MC_inducer_orientation_con 和MC_inducer_color_con,从这里开始分别称为con、diamond、orientation 和color。 color 是orientation 的子集@ 是diamond 的子集@ 是con 的子集。根据给定的Trial 对象是否在每个列表中,确定分配给它的值。我的问题是双重的,具体取决于我在每次试验中实现这些条件的方法。
如果我用一组嵌套的 if 语句评估每个子集:
if self.trial in self.MC_inducer_diamond_con:
self.trial.attr["target_shape"] = TARGET_SHAPES[rand_shape]
if self.trial in self.MC_inducer_orientation_con:
self.trial.attr["target_orientation"] = ORIENTATIONS[rand_orientation]
if self.trial in self.MC_inducer_color_con:
self.trial.attr["target_color"] = COLORS[rand_color]
else:
self.trial.attr["target_color"] = COLORS[1 if rand_color == 0 else 0]
else:
self.trial.attr["target_orientation"] = ORIENTATIONS[1 if rand_orientation == 0 else 0]
else:
self.trial.attr["target_shape"] = TARGET_SHAPES[1 if rand_shape == 0 else 0]
我遇到了一个问题,如果试验在超集中而不是子集中(例如,如果在 diamond 但不在 orientation、color 或 con 中),那么其余代码不是已评估,Trial 对象中的其余字段为空。如果不在给定集合中,代码应该做的是为每个试验分配不同的值。
如果我改为这样构造代码:
if self.trial in self.MC_inducer_diamond_con:
self.trial.attr["target_shape"] = TARGET_SHAPES[rand_shape]
elif self.trial in self.MC_inducer_diamond_con and self.trial in self.MC_inducer_orientation_con:
self.trial.attr["target_shape"] = TARGET_SHAPES[rand_shape]
self.trial.attr["target_orientation"] = ORIENTATIONS[rand_orientation]
elif self.trial in self.MC_inducer_diamond_con and self.trial in self.MC_inducer_orientation_con and self.trial in self.MC_inducer_color_con:
self.trial.attr["target_shape"] = TARGET_SHAPES[rand_shape]
self.trial.attr["target_orientation"] = ORIENTATIONS[rand_orientation]
self.trial.attr["target_color"] = COLORS[rand_color]
我遇到了一个单独的问题,我只能使用一个 else 语句来封装多种其他可能性(基本上,每个集合中存在/不存在的每种组合)。
谁能指出我正确评估这些可能性的正确方向?也许利用类继承?如果需要,我可以更具体地说明要求,但我希望即使有了这些信息也能找到解决方案。
【问题讨论】:
标签: python python-3.x if-statement