Search code examples
pythonpython-3.xodooodoo-11

how to append fields values in python list and ignore None value


i need To calculate average of some fields values and ignore none values from being calculated thats what i could done

@api.multi
def update_bar(self):
    list=[self.item.pro, self.drc.pro, self.dsc.pro, self.org.pro, 
          self.car.pro, self.model.pro, self.year.pro]
    for rec in list:
        if rec:
            self.new_list = list.append(rec)
    print(self.new_list)
    pass

Solution

  • I would do it using list comprehension

    def average_or_none(ls):
        temp = [x for x in ls if x is not None]
    
        if temp:
            return sum(temp) / len(temp)
        else:
            return None