2015-04-18 20 views
0

当我尝试这一点,我不能得到的结果,我以后 -排序字母数字序列不正确。我该如何改进它?

>>> test = { '3 Silver', '3 Oct', '4AD', '99 Reese', '1991', 'alpha', 'beta' } 
>>> sorted(test) 
['1991', '3 Oct', '3 Silver', '4AD', '99 Reese', 'alpha', 'beta'] 

这是不正确的,因为1991是最高的条目开始用数字和应该出现之前alpha

有没有人对我如何按照我想要的方式对此进行排序有任何建议?

+2

你想得到什么结果? –

+1

搜索“自然排序”。 –

+1

@JeremyBanks他希望'1991'移动到'alpha'之前。 – dbliss

回答

1

如果你想通过考虑数字对项目进行排序值(需要考虑边缘情况,但应指向正确的方向):

from itertools import takewhile, dropwhile 

test = ['3 Silver', '3 Oct', '4AD', '99 Reese', '1991', 'alpha', 'beta'] 

items = dict() 
for word in test: 
    ordlist = [] 
    ## prenumber will be zero if there are no numerical characters 
    prenumber = int(''.join(list(takewhile(lambda i: i.isdigit() , word))) or 0) 
    ## setting words that start with alpha characters to have infinity as 
    ## first item. This puts them at the end of the list for sorting. 
    ordlist.append(prenumber or float("inf")) 
    ordlist.extend((ord(ch) for ch in dropwhile(lambda i: i.isdigit(), word))) 
    items[word] = ordlist 

### sort dictionary by value 
s = sorted(zip(items.values(), items.keys())) 
print(s) 
## [([3, 32, 79, 99, 116], '3 Oct'), 
## ([3, 32, 83, 105, 108, 118, 101, 114], '3 Silver'), 
## ([4, 65, 68], '4AD'), 
## ([99, 32, 82, 101, 101, 115, 101], '99 Reese'), 
## ([1991], '1991'), 
## ([inf, 97, 108, 112, 104, 97], 'alpha'), 
## ([inf, 98, 101, 116, 97], 'beta')] 

test_sorted = [e[1] for e in s] 
## ['3 Oct', '3 Silver', '4AD', '99 Reese', '1991', 'alpha', 'beta'] 
+0

这效果很好,谢谢!但它删除了重复条目,因此输出项与输入项的数量不一定相同。 – openCivilisation

0

是的,你可以这样做,但你必须创建自己的“得分王”系统,该系统将创建顺序要:

import re 

def score(token): 
    n = re.sub(r'\D+', '', token) 
    if n: 
     n = int(n) 
    w = re.sub(r'[\d+ ]', '', token) 
    return n, w #returning a list/tuple with the most important criteria on the first place, 2nd on the second place, etc 



arr = ['3 Silver', '3 Oct', '4AD', '99 Reese', '1991', 'alpha', 'beta'] 
print sorted(arr, key=score) # ['3 Oct', '3 Silver', '4AD', '99 Reese', '1991', 'alpha', 'beta'] 
+0

感谢您的建议,但这并不是您所描述的所有规则,我可以看到您只能在这里追上4个数字。 – openCivilisation

+0

@ user1692999我刚刚学会了这个新的诀窍:返回一个列表/元组,其中第一个地方是最重要的标准,第二个地方是第二个地方等 - 将以非常优雅的方式准确地给出您想要的内容,而不会限制您确定对输入的限制。查看上面更新的'score()'函数! – alfasin

相关问题