问题描述
['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)
在两个答案都已经发布之后,我只添加了100T,但是接受的答案在稍加修改的情况下仍然有效,我在评论中发布了这个答案.为了明确起见,应对匹配^ [^ 0-9]的名称进行排序.
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)
基本原理是创建一个元组,该元组的第一个元素具有将所有字符串和所有int分组在一起的作用.不幸的是,没有一种优雅的方法可以在不使用异常的情况下确认一个字符串是否恰好是一个int,而该异常在lambda中并不那么好.我最初的解决方案使用了一个正则表达式,但是由于从lambda转到了独立功能,因此我认为我也应该选择简单的选项.
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.
这篇关于在Python中对名称列表进行排序,而忽略数字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!