【问题标题】:Excluding null values in order to divide one list by another排除空值以将一个列表除以另一个列表
【发布时间】:2012-10-05 00:32:02
【问题描述】:

我有两个列表:total_price 和 units_b,它们都包含空值,我有一个表达式将 total_price 除以 units_b:

    total_price = [None, None, 10, 20]
    units_b = [None, None, 1, 2]

    average_price = [(x/y) for x, y in zip(total_price, units_b)]

尝试运行average_price 时出现错误,提示我无法划分两个“NoneTypes”。有什么方法可以排除除法的空值但保持原始列表的完整性?

【问题讨论】:

    标签: python list null


    【解决方案1】:
    total_price = [None, None, 10, 20]
    units_b = [None, None, 1, 2]
    
    average_price = [(x/y) for x, y in zip(total_price, units_b) if x is not None and y is not None]
    

    【讨论】:

      【解决方案2】:
      average_price = [(x/y) for x, y in zip(total_price, units_b) if x is not None and y is not None]
      

      【讨论】:

        【解决方案3】:
        average_price = [(x/y) for x, y in zip(total_price, units_b) if not (x==None or y==None)]
        

        虽然你真的应该read the docs

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2012-01-05
          相关资源
          最近更新 更多