2015-04-18 19 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

相關問題