Sort list of names in Python, ignoring numbers?

 ̄綄美尐妖づ 提交于 2020-01-24 06:04:08

问题


['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.


回答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.




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


来源:https://stackoverflow.com/questions/4058455/sort-list-of-names-in-python-ignoring-numbers

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!