Python: Sort a list of strings composed of letters and numbers [duplicate]

耗尽温柔 提交于 2021-02-07 09:30:45

问题


I have a list that its elements are composed of a letters and numbers as shown below :

['H1', 'H100', 'H10', 'H3', 'H2', 'H6', 'H11', 'H50', 'H5', 'H99', 'H8'] 

I wanted to sort it, so I used the function sort, but I got as output :

>>> a = ['H1', 'H100', 'H10', 'H3', 'H2', 'H6', 'H11', 'H50', 'H5', 'H99', 'H8']
>>> print sorted(a)
['H1', 'H10', 'H100', 'H11', 'H2', 'H3', 'H5', 'H50', 'H6', 'H8', 'H99']

However, I want the output to be :

['H1', 'H2', 'H3', 'H5', 'H6', 'H8', 'H10', 'H11', 'H50', 'H99', 'H100']

Does anyone has an idea how to do this please? Thank you


回答1:


l = ['H1', 'H100', 'H10', 'H3', 'H2', 'H6', 'H11', 'H50', 'H5', 'H99', 'H8']
print sorted(l, key=lambda x: int("".join([i for i in x if i.isdigit()])))

Output:

['H1', 'H2', 'H3', 'H5', 'H6', 'H8', 'H10', 'H11', 'H50', 'H99', 'H100']


来源:https://stackoverflow.com/questions/49232823/python-sort-a-list-of-strings-composed-of-letters-and-numbers

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!