2015-07-13 90 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'] 
>>> 
相关问题