2017-03-04 53 views
5

我刚刚从python 3开始几天前。虽然节目,我遇到奇怪的情况Python找不到的类型:NoneType()> int()当找到列表的最大值时

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]]] 我的疑问是,为什么错误不是在这种情况下显示?

+1

哪个部分你困惑?如果列表中的第一个元素不相等,则不需要与第二个元素相关联。 – jonrsharpe

+0

downvote的任何特定原因? –

+0

@jonrsharpe:好的..我的疑问是为什么python向我展示错误? 对于'''[[5- [[1,2],[3,4]]],[5,[3,4],[5,6]]],[5,[[5,6- ],[7,8]]]] '''的输出为'''[5,[5,6],[7,8]]]'''和为什么相同的错误没有显示? –

回答

6

这是因为max做到这一点,当它遇到无值:

max([1, None]) 

也给出了同样的错误:

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

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

基本上最大的努力来遍历目录,找出较大值第一。但是当它达到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' with 1,给TypeError: unorderable types: str() > int()

早些时候我们合作过我们得到的错误信息是TypeError: unorderable types: NoneType() > int()

+0

感谢您澄清疑问。 –

+0

@curious_coder欢迎:) –

3

在Python 2中,这个None比较低的任何整数在某些情况下是有用的,当你需要一个你无法预测的最小值时(因为整数没有像C中那样固定的最小/最大值)。

在Python 3,这是不可能的了(而且大部分是最好的时候,它像"2"和3例如比较字符串为整数时,节省了许多烦恼。

如果你真的需要这一点,我想到了一个变通的

你可以定义一个类,这是比任何其他对象低,使用类的一个实例,而不是None

class AM: 
    def __int__(self): 
     return 0 
    def __gt__(self,other): 
     return False 
    def __repr__(self): 
     return "INF" # prints out nicely 

always_min = AM() 

a = [ 
    [5, [[1, 1, always_min], [always_min, always_min, always_min]]], 
    [5, [[1, always_min, 1], [always_min, always_min, always_min]]] 
    ] 

print(max(a)) 

我得到:

[5, [[1, 1, INF], [INF, INF, INF]]] 

这证明了抢七工作。

注意,这是一个最小的实现。 max只使用>:只定义__gt__很懒,我们需要定义其他__ge____le____lt__因此对于一般用途。