【问题标题】:how can I append None values from file to list in Python如何将文件中的 None 值附加到 Python 中的列表
【发布时间】:2017-02-27 16:12:31
【问题描述】:

我有想要在列表中保存一些属性的 Json 文件。一个属性有一些值,有时有None 值(没有数据)。当我使用append() 时,它只附加了值,而忽略了None 值。

我也需要读取 None 值。我该怎么做呢

json 喜欢:

{ "A":1,
  "B":2,
  "C":3}

{ "A":4,
  "B":,
  "C":2}

{ "A":4,
  "B":1,
  "C":2}

{ "A":4,
  "B":,
  "C":5}

如果我想将 B 保存在列表中,我需要它像 B = [2,None,1,None],但我得到的结果是 [2,1]

我使用json.loads()将json文件保存到对象,没有问题。

我确实是这样的:

for line in json_file:
    query.append(line['B'])

【问题讨论】:

  • 所以,使用条件语句:if attribute != None: ...append(attribute)
  • 你能展示你的代码吗?
  • 你的 json.loads() 的结果是什么?
  • 当我尝试重现您的问题时,由于未定义的值,json.loads 完全失败并出现 ValueError。如果它们在 json 中写为 null,则 None 会按预期附加到列表中。

标签: python list append nonetype


【解决方案1】:

您可以使用以下方案:

result = []                    # resulting list

# read file, get lists
for lst in lists:
    # get your "attributes" from current list
    for value in attributes:
        if value:                  # if value != None
            result.append(value)

# result contains required values
print result

【讨论】:

  • 您忽略了代码中的任何值,但我想将其保存到列表中
  • @AliAlgarni 您可以将它们收集到另一个列表中,例如,result_2
  • 你能告诉我result2吗?我不明白。我尝试使用 if (line ['B'] ==None) 但它没有附加空值
  • @AliAlgarni 尝试改用if not line['B']:
  • 我认为问题是你的 json 无效。请提供您的文件和代码
猜你喜欢
  • 2014-06-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-08-09
相关资源
最近更新 更多