Python 2.x sorted puzzlement

霸气de小男生 提交于 2019-12-07 22:37:44

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/10238060/python-2-x-sorted-puzzlement

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!