【问题标题】:checking for a variable multiple times多次检查变量
【发布时间】: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


【解决方案1】:

您有两个基本独立的操作:一个用于所有情况,一个用于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']]     

【讨论】:

    【解决方案2】:

    如果我是你,我会创建一个单独的函数,它接受一个参数 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)
    

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-08-08
      • 1970-01-01
      • 2020-07-07
      • 2016-08-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-21
      相关资源
      最近更新 更多