Sorting a list of names in Python, ignoring numbers?

['7', 'Google', '100T', 'Chrome', '10', 'Python'] 

I would like the result to be all numbers at the end, and the rest sorted. The numbers do not need to be sorted.

 Chrome Google Python 100T 7 10 

This is a little trickier because I sort the dictionary by value.

 def sortname(k): return get[k]['NAME'] sortedbyname = sorted(get,key=sortname) 

I only added 100T after both responses have already been sent, but the accepted answer still works with a slight change, which I posted in a comment. To clarify, you must map the name corresponding to ^ [^ 0-9].

+4
source share
2 answers

I tried to get the dictionary version, so here is the array version to extrapolate from:

 def sortkey(x): try: return (1, int(x)) except: return (0, x) sorted(get, key=sortkey) 

The basic principle is to create a tuple in which the first element has the effect of grouping all the rows together, and then all the ints. Unfortunately, there is no elegant way to confirm whether a string is an int case without using exceptions, which is not so good inside lambda. My original solution used regex, but moving from a lambda to an autonomous function, I thought that I could go for a simple option.

+3
source
 >>> l = ['7', 'Google', 'Chrome', '10', 'Python'] >>> sorted(l, key=lambda s: (s.isdigit(), s)) ['Chrome', 'Google', 'Python', '10', '7'] 

The Python sort is stable, so you can also use several sequential sorts:

 >>> m = sorted(l) >>> m.sort(key=str.isdigit) >>> m ['Chrome', 'Google', 'Python', '10', '7'] 
+1
source

All Articles