Getting the first non None value from list

后端 未结 5 1625
盖世英雄少女心
盖世英雄少女心 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条回答
  •  梦毁少年i
    2021-01-31 13:54

    I think this is the simplest way when dealing with a small set of values (will work in a list comprehension as well):

    firstVal = a or b or c or d
    

    Will always return the first non "False" value which works in some cases (given you dont expect any values which could evaluate to false as @GrannyAching points out below)

提交回复
热议问题