Sort List Of Names In Python, Ignoring Numbers?
['7', 'Google', '100T', 'Chrome', '10', 'Python'] I'd like the result to be all numbers at the end and the rest sorted. The numbers need not be sorted. Chrome Google Python 100T 7
Solution 1:
I've been struggling to get a dictionary version working, so here's the array version for you 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 who's first element has the effect of grouping all strings together then all ints. Unfortunately, there's no elegant way to confirm whether a string happens to be an int without using exceptions, which doesn't go so well inside a lambda. My original solution used a regex, but since moving from a lambda to a stand-alone function, I figured I might as well go for the simple option.
Solution 2:
>>> l = ['7', 'Google', 'Chrome', '10', 'Python']
>>> sorted(l, key=lambda s: (s.isdigit(), s))
['Chrome', 'Google', 'Python', '10', '7']
Python's sort is stable, so you could also use multiple successive sorts:
>>> m = sorted(l)
>>> m.sort(key=str.isdigit)
>>> m
['Chrome', 'Google', 'Python', '10', '7']
Post a Comment for "Sort List Of Names In Python, Ignoring Numbers?"