Lexicographically sort deeply nested lists of mixed data types in Python 3 -
in python 3, list.sort()
method lexicographical sort. in python 3, comparing list float
or int
throws typeerror
, unlike in python 2, can this:
>>> [0, 1] < 2 false
what best way accomplish old python 2 behavior?
i've tried subclassing list
, work, each of nested lists must cast subclass type nested comparisons utilize overridden comparing methods. there way of accomplishing doesn't resort recursively converting each nested lists subclass?
i'd able compare 2 lists so:
>>> = [[[0, 1], [2, 3]], [0, 1]] >>> b = [[0, 1], [2, 3]] >>> < b false
the result should false
because a[0][0]
list
, b[0][0]
int
, , in case int
s should considered less list
.
i'm looking implement sort function identical built-in python 3 list.sort
, except when list
beingness compared float
or int
, in case list
should considered larger.
since, as mentioned in python 2 docs:
most other objects of built-in types compare unequal unless same object; selection whether 1 object considered smaller or larger 1 made arbitrarily consistently within 1 execution of program.
object comparing meaningful when 2 objects of same type. relying on value returned expressions such [0, 1] < 2
should not done in programme , that's why behaviour removed python 3.
to explain further, if have list [[[0, 1], [2, 3]], [0, 1]]
, has 2 elements: [[0, 1], [2, 3]] , [0, 1]
. in order python sort them, compares internal values lexicographically, since both lists values [0, 1] , [2, 3]
first 1 , 0 , 1
second. but, then, has compare [0, 1] 0
, not of same type and, thus, comparing produces arbitrary results.
so, sorting broken.
having said above, if have lists can sorted meaningfully , cannot (because of above explanation), simple solution grab possible exception , homecoming false.
try: [0, 1] < 2 except typeerror: # homecoming or assign false. true not meaningful.
or, list.sort()
try: x.sort() except typeerror: pass # nothing. python produce meaningless results, anyway.
if want produce meaningful sorting (if makes sense), have define key function, mentioned. may rather complex, though. maybe looking @ problem different perspective better.
python list sorting python-3.x comparison
No comments:
Post a Comment