python list元素类型_Python:list包含不同元素类型时的list.sort()查询

本文探讨了在Python 3.3中遇到的列表sort方法对不同类型元素的处理,当列表包含不同类型的元素(如字符串和整数)时,尽管会引发错误,但对元素的相对顺序产生的影响。作者通过实例展示了如何避免这种意外排序,并介绍了sorted函数作为替代解决方案。
摘要由CSDN通过智能技术生成

1586010002-jmsa.png

Greetings Pythonic world. Day 4 of learning Python 3.3 and I've come across a strange property of list.sort.

I created a list of five elements: four strings, with a number in the middle. Trying to get list.sort to work gave the expected error because of mixing types:

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

>>> list.sort()

Traceback (innermost last):

File "", line 1, in

TypeError: unorderable types: int() < str()

>>> list

['b', 'a', 3, 'd', 'c']

The list is unchanged.

But then I moved the number to the end, used list.sort again, and got this:

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

>>> list.sort()

Traceback (innermost last):

File "", line 1, in

TypeError: unorderable types: int() < str()

>>> list

['a', 'b', 'c', 'd', 3]

OK, an error. But the list has sorted itself, kicking the number to the end. I couldn't find any explanation for this on this site or in Langtangen. Is there some underlying reason for this behaviour? Would it be useful in some situation?

解决方案

From the 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).

The docs don't guarantee any behaviour in particular, but the elements will more than likely be left part-way sorted. Whetever order they were in when the exception occurred, and this order can vary between implementations, or possibly (but unlikely) two subsequent runs of the program.

If you want to try to sort the items without worrying about an unfortunate re-ordering, you can use the sorted builtin function, which will return a new list rather than modify the original.

>>> 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

EDIT:

to address everyone saying something like

once it sees two different types it raises an exception

I know you are probably aware that this kind of statement is an oversimplification, but I think without being clear, it's going to cause confusion.

The following example consists of two classes A and B which support comparison with each other through their respective __lt__ methods. It shows a list mixed of these two types sorted with list.sort() and then printed in sorted order with no exceptions raised:

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)

The output of this is:

[2, 8, 9, 10, 16]

it's not vital that you understand every detail of this. It's just to illustrate that a list of mixed types can work with list.sort() if all the pieces are there

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值