Sorting Python List To Make Letters Come Before Numbers
Solution 1:
You could provide a custom key
argument which gives a lower value to strings than it does to ints:
>>> c = ['c', 'b', 'd', 'a', 4, 2, 1, 3]
>>> c.sort(key = lambda item: ([str,int].index(type(item)), item))
>>> c
['a', 'b', 'c', 'd', 1, 2, 3, 4]
Solution 2:
[sorted([letter for letter in c ifisinstance(letter, str)]) + \
sorted([number for number in c ifisinstance(number, int)]]
Should do it.
Solution 3:
Let's say we have a hybrid list like this:
c = ['s', 'a',2 , 'j', 9, 'e', 11, 't', 'k', 12, 'q']
first we need to slice up the list into two separate parts (strings and integers), sort them individually and then append them in the end. Here's one way to do it:
>>>c = sorted([i for i in c ifnotstr(i).isdigit()]) + sorted([i for i in c ifstr(i).isdigit()])
Now you get:
>>> c
['a', 'e', 'j', 'k', 'q', 's', 't', 2, 9, 11, 12]
Solution 4:
If you have a list of mixed ascii and numeric types, you need to determine what is a numeric object type. You can use the Numbers abstract base class to determine what is an instance of a number (int, float, long, complex
) class, including all derived classes (bool, Decimal, Franctions
, etc):
>>> from numbers import Number
>>> [isinstance(n, Number) for n in (0,1.1,0j,True,'a')]
[True, True, True, True, False]
Once you know what is an instance of a number, you can use a Python bool to create a primary sort key with the list item itself as a secondary key (ie, tuples comprising of [(True, 1.1), (False, 'abc'), etc]
) False
will sort lower than True
just as 0<1 in a typical ascending order sort, so that is just what we wanted.
Applying that to your list (expanded) as an example:
>>> c = ['c', 'b', 'd', 'a', 4, 2, 1, 35, 1.1, 6L, 'aac', True]
>>> sorted(c, key=lambda e: (isinstance(e, Number), e))
['a', 'aac', 'b', 'c', 'd', 1, True, 1.1, 2, 4, 6L, 35]
Note that different numeric types are being correctly sorted (1<=True<1.1<6L<35
)
Solution 5:
You can also use the cmp
parm:
c = ['c', 'b', 'd', 'a', 4, 2, 1, 3]
defcompare_function(a, b):
ifisinstance(a, str) andisinstance(b, int):
return -1ifisinstance(a, int) andisinstance(b, str):
return1return cmp(a, b)
c.sort(cmp=compare_function)
Post a Comment for "Sorting Python List To Make Letters Come Before Numbers"