几天前我刚开始使用python 3.编程时,我遇到了奇怪的情况
a = [
[5, [[1, 1, None], [None, None, None], [None, None, None]]],
[5, [[1, None, 1], [None, None, None], [None, None, None]]]
]
Run Code Online (Sandbox Code Playgroud)
max(a) 给我
回溯(最近调用最后一次):TypeError中的文件"",第1行:不可共享的类型:NoneType()> int()
但是,如果我尝试
a = [
[5, [[1, 1, None], [None, None, None], [None, None, None]]],
[5.1, [[1, None, 1], [None, None, None], [None, None, None]]]
]
Run Code Online (Sandbox Code Playgroud)
max(a) 显示器
[5.1, [[1, None, 1], [None, None, None], [None, None, None]]]
Run Code Online (Sandbox Code Playgroud)
这种行为的任何特殊原因?
更新1:我尝试了不同的东西
a = [[5, [[1,2], [3,4]]],[5,[[3,4],[5,10]]],[5,[[5,6],[7,8]]]]
Run Code Online (Sandbox Code Playgroud)
和max(a)是[5, [[5, 6], [7, 8]]]
我的疑问是,为什么错误不是在这种情况下显示?
这是因为max遇到None值时这样做:
max([1, None])
Run Code Online (Sandbox Code Playgroud)
也给出了同样的错误:
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-14-c33cf47436bc> in <module>()
----> 1 max([1,None])
TypeError: unorderable types: NoneType() > int()
Run Code Online (Sandbox Code Playgroud)
基本上,max试图迭代列表并首先找出更大的值.但是当它达到None时,它无法再进行比较,因此抛出错误.
同
a = [
[5, [[1, 1, None], [None, None, None], [None, None, None]]],
[5.1, [[1, None, 1], [None, None, None], [None, None, None]]]
]
Run Code Online (Sandbox Code Playgroud)
它比较5和5.1并认为列表与5.1更大.
当两个第一个值均为5时,它会迭代下一个项目并进入None导致错误的项目.
更新:
此示例可能有助于更好地澄清错误消息:
max([1,'2'])
Run Code Online (Sandbox Code Playgroud)
错误:
TypeError: unorderable types: str() > int()
Run Code Online (Sandbox Code Playgroud)
基本上它试图比较'2' with 1和给予TypeError: unorderable types: str() > int()
早些时候我们正在比较None with int() 1,我们得到的错误信息是TypeError: unorderable types: NoneType() > int()