Python:list包含不同元素类型时的list.sort()查询 [英] Python: list.sort() query when list contains different element types

查看:381
本文介绍了Python:list包含不同元素类型时的list.sort()查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问候Pythonic世界.学习Python 3.3的第4天,我遇到了list.sort的一个奇怪属性.

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

我创建了一个包含五个元素的列表:四个字符串,中间带有一个数字.由于混合类型,尝试使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 "<stdin>", line 1, in <module>
TypeError: unorderable types: int() < str()
>>> list
['b', 'a', 3, 'd', 'c']

列表未更改.

但是随后我将数字移到末尾,再次使用list.sort并得到了:

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 "<stdin>", line 1, in <module>
TypeError: unorderable types: int() < str()
>>> list
['a', 'b', 'c', 'd', 3]

OK,一个错误.但是列表本身已经排序完毕,将数字放在了最后.我在本网站或Langtangen中找不到任何解释.这种行为是否有一些根本原因?在某些情况下会有用吗?

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?

推荐答案

从Python 3开始文档:

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.

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

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


解决所有人都说


to address everyone saying something like

一旦看到两种不同的类型,就会引发异常

我知道您可能知道这种说法过于简单,但是我认为如果不清楚,将会引起混乱.

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.

下面的示例由两个类AB组成,它们通过各自的__lt__方法相互支持比较.它显示了将这两种类型混合在一起并以list.sort()排序的列表,然后按排序顺序打印,没有引发异常:

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)

此输出为:

[2, 8, 9, 10, 16]

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

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

这篇关于Python:list包含不同元素类型时的list.sort()查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆