如何在列表理解中检查对象是否不为空? [英] How to check if object is not None within a list comprehension?

查看:42
本文介绍了如何在列表理解中检查对象是否不为空?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我以某种方式熟悉Python中的列表推导.但是在需要检查列表是否不是无"的情况下,列表理解会失败.

I am somehow familiar with list comprehensions in Python. But in situations when I need to check if the list is not None, the list comprehension would fail.

例如

tags = v.tags
if tags:
    for t in tags:
        if t['Key'] == 'Name':
            # Do something

现在,如果标签为无",则以下列表理解失败.如果标签为空/[],则可以正常工作.我希望使用列表理解功能来检查无".

Now, if tags is None, then the following list comprehension fails. It works fine if tags is empty/[]. I would like a list comprehension that checks against None.

[k for k,v in tags if tags]:

推荐答案

这是怎么回事:

[k for k in (tags or [])]

让我们看看两种情况会发生什么:

Let's see what happens for both cases:

  • <代码>>>>标签=无

>>> [k for k in (tags or [])]
[]

  • 标签= [1、2、3]

    >>> [k for k in (tags or [])]
    [1, 2, 3]
    

  • 之所以可行,是因为仅当 bool(tags)== True 时,(标签或[])才会返回 tags .否则,它返回第二个参数,在这种情况下为 [] ,即使其布尔值也为 False .这样,我们要么遍历 tags (如果存在),要么遍历空白列表(如果不存在).

    The reason this works is because (tags or []) returns tags only if bool(tags) == True. Otherwise it returns the second argument, in this case [], even if its boolean value is also False. That way, we either loop over tags, if it exists` or over an empty list if it doesn't.

    这篇关于如何在列表理解中检查对象是否不为空?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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