python中列表元素类型可以不同吗_Python:list.sort()查询当列表包含不同的元素类型时...

从Python 3

docs:

This method sorts the list in place, using only < comparisons between

items. Exceptions are not suppressed – if any comparison operations

fail, the entire sort operation will fail (and the list will likely be

left in a partially modified state).

文档并不特别保证任何行为,但元素很可能会被部分排序.它们在发生异常时所处的顺序,并且此顺序可能在实现之间变化,或者可能(但不太可能)两次后续运行程序.

如果您想尝试对项目进行排序而不必担心不幸的重新排序,您可以使用排序的内置函数,它将返回一个新列表而不是修改原始列表.

>>> seq = ['b', 'a', 3, 'd', 'c']

>>> try:

... seq = sorted(seq) # if sorted fails, result won't be assigned

... except Exception: # you may only want TypeError

... pass

...

>>> seq

['b', 'a', 3, 'd', 'c'] # list unmodified

编辑:

解决每个人说的话

once it sees two different types it raises an exception

我知道你可能已经意识到这种说法过于简单了,但我认为如果不清楚,它会引起混淆.

以下示例包含两个类A和B,它们通过各自的__lt__方法支持相互比较.它显示了使用list.sort()排序的这两种类型的混合列表,然后按排序顺序打印,没有异常引发:

class A:

def __init__(self, value):

self.a = value

def __lt__(self, other):

if isinstance(other, B):

return self.a < other.b

else:

return self.a < other.a

def __repr__(self):

return repr(self.a)

class B:

def __init__(self, value):

self.b = value

def __lt__(self, other):

if isinstance(other, A):

return self.b < other.a

else:

return self.b < other.b

def __repr__(self):

return repr(self.b)

seq = [A(10), B(2), A(8), B(16), B(9)]

seq.sort()

print(seq)

这个输出是:

[2, 8, 9, 10, 16]

了解每一个细节并不重要.这只是为了说明混合类型列表可以与list.sort()一起使用,如果所有部分都存在的话

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值