使用python对复杂字符串进行排序
我有一个包含数字和字符的数组,例如,['a3','c1','b2',],我想用每个元素中的数字对它进行排序 我尝试了下面的代码,但没有成功使用python对复杂字符串进行排序,python,Python,我有一个包含数字和字符的数组,例如,['a3','c1','b2',],我想用每个元素中的数字对它进行排序 我尝试了下面的代码,但没有成功 def getKey(item): item.split(' ') return item[1] x = ['A 3', 'C 1', 'B 2'] print sorted(x, key=getKey(x)) 你所拥有的,加上对不起作用的内容的评论:p def getKey(item): item.split(' ') #withou
def getKey(item):
item.split(' ')
return item[1]
x = ['A 3', 'C 1', 'B 2']
print sorted(x, key=getKey(x))
你所拥有的,加上对不起作用的内容的评论: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]))
为了安全起见,我建议你去掉所有东西,除了数字
>>> 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']
这是一种方法:
>>> 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']
>>>
打印排序(x,key=getKey(x))
->打印排序(x,key=getKey)
。键需要一个函数,因此,返回项[1]
=>返回int(项[1])
除非您希望19“未工作”不是问题。运行代码时会发生什么?另外def getKey(item):返回int(item.split()[1])
我喜欢“E”的测试用例和数字的剥离。这使得它更加健壮。