如果list不为空,则用列表理解遍历字典列表

时间:2019-12-29 08:35:11

标签: python list-comprehension

我要一些数据,有时json中不存在所请求的字段。我要遍历的是一列字典,而我正在寻找该字典中的特定键。

这件事按预期工作,但希望将其转换为列表理解格式:

    if x is not None:
        for item in x:
            print(item['param'])

我尝试了不同的事情:

# This works if data is present
y = [i['param'] for i in x if x is not None]

# But fails when it is not
TypeError: 'NoneType' object is not iterable

我认为应该先执行'if'语句,但是当前的工作方式是首先执行值。我一直在想这样的事情:

y = [x if x is not None else item['param'] for item in x]

但是这也不起作用。

有人可以向我解释我在做什么错吗?

2 个答案:

答案 0 :(得分:0)

您可以阅读https://www.python.org/dev/peps/pep-0289/来了解生成器表达式。

[i['param'] for i in x if x is not None]
# equal
line 1: for i in x:
line 2:     if x is not None:
        ...
# Your logic is to first determine whether the two tables exist and then iterate, 
# and the logic of the code is to iterate first and then determine whether the list exists. 
# The fatal problem is that when the null value is iterated, 
# it will report an error and cannot enter the judgment logic.

# You can code like follows:
if x:
    y = [i['param'] for i in x]

答案 1 :(得分:-3)

解决方案:
给x一个空列表的默认值,因此,如果它没有收到值,则它是[],而不是None
然后可以使用

y = [i['param'] for i in x if x]

错误:

y = [x if x is not None else item['param'] for item in x]

此处的“非”应删除。

说明:
如果您运行的行尝试遍历None,即使该部分不会运行,python也会将其视为语法错误。您对此无能为力。

相关问题