【发布时间】:2020-09-17 20:51:46
【问题描述】:
我正在编写一些分析脚本,其中需要满足很多条件才能正确实现代码。代码看起来很乱,因为我必须不断检查某些事情。这是我的问题的简化版本。
我有一个变量名“measurement_type”。
measurement_type 可以是 3 个值,“transmission”、“reflection”、“both”。我需要执行 2 组不同的指令,具体取决于 measure_type 是否在(“传输”或“反射”)或 measure_type ==“两者”
我将在这里简化我的问题,因为我认为实际代码并不重要。
如果measurement_type in ("transmission","reflection") 我只需要运行这个:
table = pd.DataFrame(stuff)
arr = []
for num in table:
arr.append(num)
plt.plot(stuff)
因为我必须考虑measurement_type == 'both',所以我也必须运行它来检查:
table1 = pd.DataFrame(stuff)
arr1 = []
if measurement_type == 'both':
table2 = pd.DataFrame(stuff) #always same dimensions as table1
arr2 = []
for j in range(len(table)):
arr1.append(table['data'][j])
if measurement_type == 'both':
arr2.append(table2['data'][j]
plt.plot(stuff)
if measurement_type == 'both':
plt.plot(more stuff)
我不得不运行后者,因为我需要注意measurement_type = 'both' 的可能性
这已经失控了,因为我必须检查“两者”是否存在。
有没有更好的方法来做到这一点?
我宁愿不必一遍又一遍地输入if measurement_type == 'both',因为我的分析脚本变得更长更复杂。
【问题讨论】:
-
您的问题不清楚。根据您的描述,如果您在第二段代码中,您已经知道它是
both;不用再检查,更不用说再检查两次了。 -
我仍然需要检查
both,因为如果不是两者兼有而我这样做arr2.append,它会给我一个变量不存在错误。如果我不清楚,对不起,但我的意思是说我正在运行第二个代码块来代替第一个代码块。这是因为我希望使用相同的代码来处理measurement_type的所有可能值 -
要运行第二个块代替第一个块,您已经验证它是
both。请在该代码的开头查看您自己的评论:If measurement_type == 'both' I am running this:如果情况不是,那么我们需要您向我们提供准确的逻辑示例。请提供预期的minimal, reproducible example。 -
对不起,你是对的,我已经做了相应的修改
标签: python if-statement coding-style