多次检查变量

问题描述

我正在编写一些分析脚本,在这些脚本中需要满足很多条件才能正确实现代码。该代码看起来很乱,因为我必须继续检查某些内容。这是我的问题的简化版本。

我有一个变量名'measurement_type'。

measurement_type可以是3个值,“ transmission”,“ reflection”和“ both”。我需要执行两组不同的指令集,具体取决于measurement_type是处于“传输”还是“反射”状态或measurement_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'的可能性 这已经失控了,因为我必须对“ both”和“ both”是否存在进行检查。

是否有更好的方法? 随着分析脚本变得越来越长和越来越复杂,我宁愿不必一遍又一遍地输入if measurement_type == 'both'

解决方法

您有两个基本上独立的操作:一个用于所有情况,一个用于both。如您所见,您的原始代码有点难以理解:

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]

提取独立于both的部分;然后针对您的特殊情况进行检查并进行适当处理:

arr1 = list(table['data'])   # This should be a straight conversion; no need to loop.
if measurement_type == 'both':
    arr2 = list(table2['data'])  #Similar conversion

如果您的table类型没有实现list转换,那么至少使用理解而不是循环:

arr1 = [c for c in table['data']]     
,

如果您是我,我将创建一个单独的函数,该函数接受参数measurement_type并将操作分成两个逻辑部分。像这样:

def plot_data(measurement_type):
   table1 = pd.DataFrame(stuff)
   arr1 = []
   for j in range(len(table)):
       arr1.append(table['data'][j])
   plt.plot(stuff)
   
   if measurement_type == 'both':
       table2 =  pd.DataFrame(stuff) #always same dimensions as table1
       arr2 = []
       for j in range(len(table)):
           arr2.append(table2['data'][j]
       plt.plot(more stuff)

这可能不是最有效的(您可能需要执行两次相同的循环),但是如果性能不成问题,将代码分解为更多逻辑部分可能会很有用。