gpt4 book ai didi

python - 在 Python 3 中按字典顺序对混合数据类型的深度嵌套列表进行排序

转载 作者:太空宇宙 更新时间:2023-11-03 11:51:58 26 4
gpt4 key购买 nike

在 Python 3 中,list.sort() 方法将执行字典排序。但在 Python 3 中,将列表与 floatint 进行比较会抛出 TypeError,这与在 Python 2 中不同,您可以在其中执行此操作:

>>> [0, 1] < 2
False

实现旧 Python 2 行为的最佳方法是什么?

我试过对 list 进行子类化,但要使其工作,每个嵌套列表都必须转换为子类类型,以便所有嵌套比较都使用覆盖的比较方法。有没有一种方法可以不诉诸递归地将每个嵌套列表转换为子类来实现这一目标?

我希望能够像这样比较两个列表:

>>> a = [[[0, 1], [2, 3]], [0, 1]]
>>> b = [[0, 1], [2, 3]]
>>> a < b
False

结果应该是 False 因为 a[0][0] 是一个 listb[0][0 ] 是一个 int,在我的例子中,int 应该始终被认为小于 list

编辑:

我想实现一个与内置 Python 3 list.sort 相同的排序函数,除非将 listfloatint,在这种情况下,list 应始终被视为更大。

最佳答案

因为,as mentioned in the Python 2 docs :

Most other objects of built-in types compare unequal unless they are the same object; the choice whether one object is considered smaller or larger than another one is made arbitrarily but consistently within one execution of a program.

对象比较只有在两个对象属于同一类型时才有意义。依赖表达式返回的值,例如 [0, 1] < 2不应在程序中完成,这就是此行为已从 Python 3 中删除的原因。

为了进一步解释,如果您有列表 [[[0, 1], [2, 3]], [0, 1]] ,这有两个元素:
[[0, 1], [2, 3]] and [0, 1] .为了让 python 对它们进行排序,它按字典顺序比较它们的内部值,因为它们都是具有值 [0, 1] and [2, 3] 的列表。对于第一个和0 and 1第二个。但是,它必须比较 [0, 1] with 0 ,它们不是同一类型,因此比较会产生任意结果。

所以,这种排序是错误的。

综上所述,如果您有一些列表可以进行有意义的排序而一些列表不能(由于上述解释),一个简单的解决方案是捕获可能的异常,然后返回 False。

try:
[0, 1] < 2
except TypeError:
# return or assign False. True is not actually meaningful.

或者,对于 list.sort()

try:
x.sort()
except TypeError:
pass # Do nothing. Python would produce meaningless results, anyway.

如果您想产生有意义的排序(如果这确实有意义),那么您将必须定义一个关键函数,如前所述。不过,这可能相当复杂。也许从不同的角度看你的问题会更好。

关于python - 在 Python 3 中按字典顺序对混合数据类型的深度嵌套列表进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24291448/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com