Python 2.x 排序困惑 [英] Python 2.x sorted puzzlement
本文介绍了Python 2.x 排序困惑的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在 Python 2.x 中有一个部分排序的元组.
为什么 Python 会反转而不是排序?
<预><代码>>>>数据 = (u'a', (1,), 'b', u'b', (2,), 'c', u'c', (3,), 'd', u'd',(4,), 'e')>>>排序(数据)==列表(反转(数据))真的我期待 Python 3.
解决方案
它失败了,因为排序算法依赖于元素的总排序,这意味着传递<
.
unicode 字符串、元组和字符串的顺序不是可传递的:
<预><代码>>>>a = 'x'>>>b = (1,)>>>c = u'x'>>><乙真的>>><C真的>>><C错误的即,您的列表不存在有效的排序.至少不是使用默认比较器.
I have a partially sorted tuple in Python 2.x.
Why Python reverse it instead of sort it?
>>> data = (u'a', (1,), 'b ', u'b', (2,), 'c ', u'c', (3,), 'd ', u'd', (4,), 'e')
>>> sorted(data) == list(reversed(data))
True
I look forward to Python 3.
解决方案
It fails because the sorting algorithm depends on a total ordering of the elements, which implies transitive <
.
The ordering of unicode strings, tuples, and strings isn't transitive:
>>> a = 'x'
>>> b = (1,)
>>> c = u'x'
>>> a < b
True
>>> b < c
True
>>> a < c
False
I.e., there exists no valid sort for your list. At least not with the default comparator.
这篇关于Python 2.x 排序困惑的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文