2015-07-13 48 views
-1

我有一個包含數字和字符的數組,例如['A 3','C 1','B 2'],我想用每個元素中的數字對它進行排序。使用python對複雜字符串進行排序

我嘗試下面的代碼,但沒有奏效

def getKey(item): 
    item.split(' ') 
    return item[1] 
x = ['A 3', 'C 1', 'B 2'] 

print sorted(x, key=getKey(x)) 
+0

'打印排序(X,鍵=信息getKey(X))' - >'打印排序(X,鍵=信息getKey)'。除非你想要19 <2 – NightShadeQueen

+0

另外,'return item [1]'=>'return int(item [1])'不是問題。當你運行你的代碼時會發生什麼? – NightShadeQueen

+0

「不起作用」,否則鍵盤預期功能 –

回答

0

你有什麼,加上意見有什麼不工作:P

def getKey(item): 
    item.split(' ') #without assigning to anything? This doesn't change item. 
        #Also, split() splits by whitespace naturally. 
    return item[1] #returns a string, which will not sort correctly 
x = ['A 3', 'C 1', 'B 2'] 

print sorted(x, key=getKey(x)) #you are assign key to the result of getKey(x), which is nonsensical. 

它應該是什麼

print sorted(x, key=lambda i: int(i.split()[1])) 
2

爲了安全起見,我建議你去掉所有的數字。

>>> import re 
>>> x = ['A 3', 'C 1', 'B 2', 'E'] 
>>> print sorted(x, key=lambda n: int(re.sub(r'\D', '', n) or 0)) 
['E', 'C 1', 'B 2', 'A 3'] 

用你的方法;

def getKey(item): 
    return int(re.sub(r'\D', '', item) or 0) 

>>> print sorted(x, key=getKey) 
['E', 'C 1', 'B 2', 'A 3'] 
+1

我喜歡'E'的測試用例並且去掉數字。這使得這更強大。 – Ross

-2

這是爲了做到這一點的一種方法:

>>> x = ['A 3', 'C 1', 'B 2'] 
>>> y = [i[::-1] for i in sorted(x)] 
>>> y.sort() 
>>> y = [i[::-1] for i in y] 
>>> y 
['C 1', 'B 2', 'A 3'] 
>>> 
相關問題