作者热门文章
- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
几天前我刚开始使用 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/
我是一名优秀的程序员,十分优秀!