user479870
user479870

Reputation:

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
10

It's slightly more complicated though, because I sort a dictionary by value.

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

I only added 100T after both answers were posted already, but the accepted answer still works with a slight modification I posted in a comment. To clarify, a name matching ^[^0-9] should be sorted.

Upvotes: 4

Views: 2978

Answers (2)

Marcelo Cantos
Marcelo Cantos

Reputation: 185970

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.

Upvotes: 3

adw
adw

Reputation: 5021

>>> 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']

Upvotes: 1

Related Questions