Getting the first non None value from list

后端 未结 5 1620
盖世英雄少女心
盖世英雄少女心 2021-01-31 13:25

Given a list, is there a way to get the first non-None value? And, if so, what would be the pythonic way to do so?

For example, I have:

  • a = objA.addr
5条回答
  •  礼貌的吻别
    2021-01-31 14:11

    When the items in your list are expensive to calculate such as in

    first_non_null = next((calculate(x) for x in my_list if calculate(x)), None)
    
    # or, when receiving possibly None-values from a dictionary for each list item:
    
    first_non_null = next((my_dict[x] for x in my_list if my_dict.get(x)), None)
    

    then you might want to avoid the repetitive calculation and simplify to:

    first_non_null = next(filter(bool, map(calculate, my_list)), None)
    
    # or:
    
    first_non_null = next(filter(bool, map(my_dict, my_list)), None)
    

    Thanks to the usage of a generator expression, the calculations are only executed for the first items until a truthy value is generated.

提交回复
热议问题