sort order for strings of digits

wxjmfauth at gmail.com wxjmfauth at gmail.com
Thu Nov 1 04:52:58 EDT 2012


Le mercredi 31 octobre 2012 16:17:19 UTC+1, djc a écrit :
> I learn lots of useful things from the list, some not always welcome. No 
> 
> sooner had I found a solution to a minor inconvenience in my code, than 
> 
> a recent thread here drew my attention to the fact that it will not work 
> 
> for python 3. So suggestions please:
> 
> 
> 
>      TODO 2012-10-22: sort order numbers first then alphanumeric
> 
>  >>> n
> 
> ('1', '10', '101', '3', '40', '31', '13', '2', '2000')
> 
>  >>> s
> 
> ('a', 'ab', 'acd', 'bcd', '1a', 'a1', '222 bb', 'b a 4')
> 
> 
> 
>  >>> sorted(n)
> 
> ['1', '10', '101', '13', '2', '2000', '3', '31', '40']
> 
>  >>> sorted(s)
> 
> ['1a', '222 bb', 'a', 'a1', 'ab', 'acd', 'b a 4', 'bcd']
> 
>  >>> sorted(n+s)
> 
> ['1', '10', '101', '13', '1a', '2', '2000', '222 bb', '3', '31', '40', 
> 
> 'a', 'a1', 'ab', 'acd', 'b a 4', 'bcd']
> 
> 
> 
> 
> 
> 
> 
> Possibly there is a better way but for Python 2.7 this gives the 
> 
> required result
> 
> 
> 
> Python 2.7.3 (default, Sep 26 2012, 21:51:14)
> 
> 
> 
>  >>> sorted(int(x) if x.isdigit() else x for x in n+s)
> 
> [1, 2, 3, 10, 13, 31, 40, 101, 2000, '1a', '222 bb', 'a', 'a1', 'ab', 
> 
> 'acd', 'b a 4', 'bcd']
> 
> 
> 
> 
> 
> [str(x) for x in sorted(int(x) if x.isdigit() else x for x in n+s)]
> 
> ['1', '2', '3', '10', '13', '31', '40', '101', '2000', '1a', '222 bb', 
> 
> 'a', 'a1', 'ab', 'acd', 'b a 4', 'bcd']
> 
> 
> 
> 
> 
> But not for Python 3
> 
> Python 3.2.3 (default, Oct 19 2012, 19:53:16)
> 
> 
> 
>  >>> sorted(n+s)
> 
> ['1', '10', '101', '13', '1a', '2', '2000', '222 bb', '3', '31', '40', 
> 
> 'a', 'a1', 'ab', 'acd', 'b a 4', 'bcd']
> 
> 
> 
>  >>> sorted(int(x) if x.isdigit() else x for x in n+s)
> 
> Traceback (most recent call last):
> 
>    File "<stdin>", line 1, in <module>
> 
> TypeError: unorderable types: str() < int()
> 
>  >>>
> 
> 
> 
> The best I can think of is to split the input sequence into two lists, 
> 
> sort each and then join them.
> 
> 
> 
> 
> 
> -- 
> 
> djc

>>> # Py 3.2.3
>>> z = ['1', '10', '101', '13', '1a', '2', '2000',
...     '222 bb', '3', '31', '40', 'a', 'a1', 'ab',
...     'acd', 'b a 4', 'bcd'
... ]
>>> n, s = [], []
>>> for e in z:
...     if e.isdigit():
...         n.append(int(e))
...     else:
...         s.append(e)
...         
>>> n.sort()
>>> s.sort()
>>> ns = [str(e) for e in n]
>>> ns.extend(s)
>>> ns
['1', '2', '3', '10', '13', '31', '40', '101', '2000', '1a',
'222 bb', 'a', 'a1', 'ab', 'acd', 'b a 4', 'bcd']

jmf



More information about the Python-list mailing list