【问题标题】:TypeError: 'NoneType' object is not iterable for a small range problem I am trying to work onTypeError:对于我正在尝试处理的小范围问题,“NoneType”对象不可迭代
【发布时间】:2021-07-12 02:17:50
【问题描述】:

我正在学习如何编码。对所有这些东西都很陌生。但是为什么一点点代码给我一个“TypeError:'NoneType'对象不可迭代”错误。我在 Jupyter 中

ranges = []
for i in range(len(Y)):
     x = max(Y[i]) - min(Y[i])
     ranges.append(x)

提前致谢!

【问题讨论】:

  • 什么是Y?它有None
  • Y[i]Nonei 的值之一。找到它并修复它。您可以将if Y[i] is None: print(i) 添加到您的循环中以找到它。

标签: python data-science


【解决方案1】:

正如@TomKarzes 指出的那样,Y[i]None 至少有一个i 值。另外,请注意,在这种情况下,您没有理由对i 进行索引:只需对Y 的元素进行索引,因为这增加了可读性。结合对None的检查,我们得到:

ranges = []
for item in Y:
    if item is None:
        pass # this means do nothing. You could also append None
    else:
        x = max(item) - min(item)
        ranges.append(x)

最后,我要指出的是,在 Python 中,您可以通过使用列表推导在一行中完成所有这些操作

ranges = [max(item) - min(item) for item in Y if item is not None]

【讨论】:

    猜你喜欢
    • 2012-08-25
    • 1970-01-01
    • 2017-02-20
    • 2017-08-29
    • 2016-08-30
    • 2014-11-21
    相关资源
    最近更新 更多