Getting the first non None value from list

后端 未结 5 1623
盖世英雄少女心
盖世英雄少女心 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:06

    You can use next():

    >>> a = [None, None, None, 1, 2, 3, 4, 5]
    >>> next(item for item in a if item is not None)
    1
    

    If the list contains only Nones, it will throw StopIteration exception. If you want to have a default value in this case, do this:

    >>> a = [None, None, None]
    >>> next((item for item in a if item is not None), 'All are Nones')
    All are Nones
    

提交回复
热议问题