【问题标题】:Better way to check variable to avoid multiple conditions for multiple variables检查变量的更好方法以避免多个变量的多个条件
【发布时间】:2019-09-19 19:44:14
【问题描述】:

我有下面的示例代码,其中定义了三个变量job_Nameout_Fileerr_File

现在,如果任何变量或所有变量为空且未定义,我希望将其从打印语句中删除

job_Name = "Test"
out_File = "/tmp/123"
err_File = "/tmp/321"

print("Job Name {0},Output {1}, Error {2}".format(job_Name,out_File,err_File))

ie: if job_Name is empty 它应该打印出来:

Output  Error
/tmp/123 /tmp/321

假设out_Fileerr_File 没有定义它应该只打印job_Name

Job Name 
Test

这可以通过链条件ifelse 等来完成。但是看看是否可以避免这种情况,因为我们有多个这样的变量并通过一些更智能或其他优雅的方式来实现。

【问题讨论】:

    标签: python if-statement conditional-statements


    【解决方案1】:

    有点扩展,但可以解决问题:

    job_Name = "Test"
    out_File = "/tmp/123"
    err_File = "/tmp/321"
    
    headers = ''
    output = ''
    if job_Name:
        headers += 'Job Name\t'
    if out_File:
        headers += 'Output\t'
    if err_File:
        headers += 'Error\t'
    
    for val in [job_Name, out_File, err_File]:
        if val:
            output += val + '\t'
    
    print(headers)
    print(output)
    

    如果您的变量具有要打印的所需名称,另一种方法可能是:

    def retrieve_name(var):
        # prints the given variable's name
        import inspect
        callers_local_vars = inspect.currentframe().f_back.f_locals.items()
        return [var_name for var_name, var_val in callers_local_vars if var_val is var]
    
    
    job_Name = "Test"
    out_File = "/tmp/123"
    err_File = "/tmp/321"
    
    headers = ''
    output = ''
    
    for val in [job_Name, out_File, err_File]:
        if val:
            headers += str(retrieve_name(val)[0]) + '\t'
            output += val + '\t'
    
    print(headers)
    print(output)
    

    【讨论】:

      【解决方案2】:

      也许这对您来说是一个解决方案,但这取决于这些变量的来源:

      error_data = {
          "Job Name": "Test",
          "Output": "/tmp/123",
          "Error": "/tmp/321"
      }
      line = []
      for description, value in error_data.items():
          if(value):
              line.append("{description} {value}".format(description=description, value=value))
      
      print(",".join(line))
      

      【讨论】:

        【解决方案3】:

        也许你可以做

        print(f"{'Job Name' + job_Name + ', ' if job_Name else ''}{'Output' + out_File + ', ' if out_File else ''}{'Error' + err_File + ', ' if err_File else ''}")
        

        【讨论】:

        • ...但就逗号而言,它既不好也不是完美的解决方案
        猜你喜欢
        • 2015-09-15
        • 1970-01-01
        • 2014-03-05
        • 2015-03-06
        • 2019-09-25
        • 2018-03-01
        • 1970-01-01
        • 2015-02-18
        • 1970-01-01
        相关资源
        最近更新 更多