【问题标题】:Python iteration exclude type not bool, float, int or not NoneType (TypeError: 'NoneType' object is not iterable)Python 迭代排除类型不是 bool、float、int 或非 NoneType (TypeError: 'NoneType' object is not iterable)
【发布时间】:2021-10-20 09:37:52
【问题描述】:

我正在尝试迭代 JSON 文件及其元素。问题是,如果第一次迭代(元素)的值是 bool/float/int 或 NoneType 类型,则会引发错误消息。

这是我的尝试(它适用于 bool、float 和 int 但会抛出 TypeError: 'NoneType' object is not iterable):

for element in json:
    if type(element) != bool \
                    and type(element) != float \
                    and type(element) != int \
                    and type(element) is not None:
    for value in json[element]:
        print(value)

还有没有办法缩短 Python 中的代码?

【问题讨论】:

  • 第二个 for 循环的缩进错误。

标签: python loops if-statement iteration


【解决方案1】:

在 Python 中,通常只执行此操作并处理任何异常。

for element in json:
    try:
        for value in element:
            print(value)
    except TypeError:
        pass

另外,您确定要迭代 json[element] 还是只在内部 for 循环中迭代 element

【讨论】:

  • 对不起,我的意思是迭代元素。这不是我只是试图破坏它的原始代码:) 但实际问题可以通过正确的 If 语句来解决。但是谢谢我正在尝试这个解决方案:)
猜你喜欢
  • 1970-01-01
  • 2021-08-08
  • 2014-02-17
  • 2020-06-17
  • 2017-10-14
  • 2020-05-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多