从列表中获取第一个非None值 [英] Getting the first non None value from list

查看:111
本文介绍了从列表中获取第一个非None值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给出一个列表,有没有办法获得第一个非值?而且,如果是这样,这样做的pythonic方式是什么?

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?

例如,我有:

  • a = objA.addreses.country.code
  • b = objB.country.code
  • c = None
  • d = 'CA'
  • a = objA.addreses.country.code
  • b = objB.country.code
  • c = None
  • d = 'CA'

在这种情况下,如果a为None,那么我想得到b.如果a和b都为None,我想得到d.

In this case, if a is None, then I would like to get b. If a and b are both None, the I would like to get d.

当前我正在按照(((a or b) or c) or d)的方式进行操作,还有另一种方法吗?

Currently I am doing something along the lines of (((a or b) or c) or d), is there another way?

推荐答案

您可以使用 next() :

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

如果列表仅包含None,它将抛出StopIteration异常.如果要在这种情况下使用默认值,请执行以下操作:

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

这篇关于从列表中获取第一个非None值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆