Python 不可排序类型 : NoneType() > int() when finding max of a list

标签 python python-3.x

几天前我刚开始使用 python 3。在编程的时候遇到了奇怪的情况

a = [
     [5, [[1, 1, None], [None, None, None], [None, None, None]]], 
     [5, [[1, None, 1], [None, None, None], [None, None, None]]]
    ]

max(a) 给我

Traceback (most recent call last): File "", line 1, in TypeError: unorderable types: NoneType() > int()

但如果我尝试

a = [
     [5, [[1, 1, None], [None, None, None], [None, None, None]]], 
     [5.1, [[1, None, 1], [None, None, None], [None, None, None]]]
    ]

max(a) 显示

[5.1, [[1, None, 1], [None, None, None], [None, None, None]]]

这种行为有什么特别的原因吗?

更新 1: 我尝试了一些不同的东西

 a = [[5, [[1,2], [3,4]]],[5,[[3,4],[5,10]]],[5,[[5,6],[7,8]]]]

max(a)[5, [[5, 6], [7, 8]]] 我的疑问是为什么在这种情况下没有显示错误?

最佳答案

这是因为 max 在遇到 None 值时会这样做:

max([1, None])

同样报错:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-14-c33cf47436bc> in <module>()
----> 1 max([1,None])

TypeError: unorderable types: NoneType() > int()

基本上 max 试图遍历列表并首先找出较大的值。但当它达到 None 时,它​​无法再进行比较,因此会抛出错误。

a = [
     [5, [[1, 1, None], [None, None, None], [None, None, None]]], 
     [5.1, [[1, None, 1], [None, None, None], [None, None, None]]]
    ]

它比较 5 和 5.1,并认为 5.1 更大的列表。

当两个第一个值都是 5 时,它会迭代下一个项目并遇到 None 导致错误。

更新:

此示例可能有助于更好地阐明错误消息:

max([1,'2'])

错误:

TypeError: unorderable types: str() > int()

基本上它试图将 '2' 与 1 进行比较并给出 TypeError: unorderable types: str() > int()

早些时候我们正在比较 None 和 int() 1,我们得到的错误消息是 TypeError: unorderable types: NoneType() > int()

关于Python 不可排序类型 : NoneType() > int() when finding max of a list,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42594640/

相关文章:

python - 递归函数(阶乘)用 IntOverflow 打破了 Clojure 而不是 Python

python - 如何阻止 Vim 突出显示 python 文件中的尾随空格

python-3.x - 如何通过 API 接受 Github 仓库邀请?

python-3.x - 如何根据同一数据框中的另一列计算 Pandas 数据框中的值

python - 如何使用 python 在 SOAPpy 中设置 XML 属性?

python - 如何在Python 3.5.1中使用* args在列表中进行计算

python-3.x - 处理巨大 .csv 的最佳方法

python - map 与列表;为什么会有不同的行为?

python-3.x - 使用 Python Factor_Analyzer 进行因子分析

python - 如何使用 openpyxl 正确格式化日期?