python - 在python中,有没有办法自动替换缺失值?

标签 python list

我正在尝试解析由对象数组组成的 JSON 对象。每个对象包含几个字段,但字段经常丢失。这是一个例子:

{
    'objects' : [{
        'fieldA' : 1,
        'fieldB' : 2,
        'fieldC' : 3,
    },
    {
        'fieldA' : 7,
        'fieldC' : 8,
    },
    {},
    {
        'fieldB' : 1,
        'fieldC' : 0,
    }]
}

我想将每个字段转换成一个列表,保留对象的顺序,相当于:

fieldA = [1,7,"Missing","Missing"]
fieldB = [2,"Missing","Missing",1]
fieldC = [3,8,"Missing",0]

有没有简单的方法来做到这一点?我可以想出一些方法来做到这一点,其中涉及大量“if”和“in”语句以及对列表的重复迭代。但似乎应该有一种更 pythonic 的方式来做到这一点,比如:

fieldA = [ (obj.fieldA | "missing") for obj in json.objects]

python 语法允许这样的事情吗?

最佳答案

你需要 dict.get() 方法:

fieldA = [obj.get("fieldA", "missing") for obj in json["objects"]]

请注意,字典的项目是通过 ["key"] 访问的,而不是通过 .key 访问的。

关于python - 在python中,有没有办法自动替换缺失值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8313464/

相关文章:

Python Plotly 条形图对 csv 中的项目进行计数

python - 我可以使用别名从 python 脚本执行程序吗

python - 在python中复制列表

c# - 在 C# 中混合列表<string>

python - 元组删除列表

JAVA搜索列表字段

Python/PyQuery : Unable to find vcvarsall. bat ?

python - 如何阻止用户输入 1582 年之前的年份 (Python)

python - 在 Python 中从另一个列表中减去一个列表

python - 为什么同一解决方案的逐位算法的运行时间不同