开发者

Sort list of names in Python, ignoring numbers?

开发者 https://www.devze.com 2023-01-22 10:49 出处:网络
[\'7\', \'Goo开发者_JAVA技巧gle\', \'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.
['7', 'Goo开发者_JAVA技巧gle', '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.


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.


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

精彩评论

暂无评论...
验证码 换一张
取 消