排序Python列表有异常

时间:2017-12-04 05:00:47

标签: python list sorting

如何按字母顺序对python列表进行排序,同时考虑列表项后面的编号。请参阅下面的示例和用于排序的代码。 请注意,如果数字低于10,则无法在代码中插入零。

原始列表:

  

[' drawing-n-3',' drawing-n-2',' drawing-n-1',' drawing-n -7&#39 ;,   ' drawing-n-6',' drawing-n-5',' drawing-n-4',' drawing-n-9&#39 ;,   ' drawing-n-8',' drawing-n-16',' drawing-n-15',' drawing-n-14&#39 ;,   ' drawing-n-13',' drawing-n-12',' drawing-n-11',' drawing-n-10&#39 ;,   '绘图N-17']

排序列表:

  

[' drawing-n-1',' drawing-n-10',' drawing-n-11',' drawing-n -12&#39 ;,   ' drawing-n-13',' drawing-n-14',' drawing-n-15',' drawing-n-16&#39 ;,   ' drawing-n-17',' drawing-n-2',' drawing-n-3',' drawing-n-4&#39 ;,   ' drawing-n-5',' drawing-n-6',' drawing-n-7',' drawing-n-8' drawing-n-8&#39 ;,   '绘图N-9']

期望列表输出:

  

[' drawing-n-1',' drawing-n-2',' drawing-n-3',' drawing-n -4&#39 ;,   ' drawing-n-5',' drawing-n-6',' drawing-n-7',' drawing-n-8' drawing-n-8&#39 ;,   ' drawing-n-9',' drawing-n-10',' drawing-n-11',' drawing-n-12&#39 ;,   ' drawing-n-13',' drawing-n-14',' drawing-n-15',' drawing-n-16&#39 ;,   '绘图N-17']

代码:

dwg_number_keys = [key for key in kwargs if key.startswith("drawing-n-")]
print dwg_number_keys
print sorted(dwg_number_keys, key=str.lower)

3 个答案:

答案 0 :(得分:0)

将其从字符串解析为整数以进行排序: -

>>> begin = len("drawing-n-")
>>> sorted(dwg_number_keys, key=lambda s:int(s[len("drawing-n-"):]))
['drawing-n-1', 'drawing-n-2', 'drawing-n-3', 'drawing-n-4', 'drawing-n-5', 'drawing-n-6', 'drawing-n-7', 'drawing-n-8', 'drawing-n-9', 'drawing-n-10', 'drawing-n-11', 'drawing-n-12', 'drawing-n-13', 'drawing-n-14', 'drawing-n-15', 'drawing-n-16', 'drawing-n-17']

答案 1 :(得分:0)

像这样:

>>> my_list = ['drawing-n-3', 'drawing-n-2', 'drawing-n-1', 'drawing-n-7', 'drawing-n-6', 'drawing-n-5', 'drawing-n-4', 'drawing-n-9', 'drawing-n-8', 'drawing-n-16', 'drawing-n-15', 'drawing-n-14', 'drawing-n-13', 'drawing-n-12', 'drawing-n-11', 'drawing-n-10', 'drawing-n-17']
>>> sorted(my_list, key=lambda s:int(s[s.rindex('-')+1:]))
['drawing-n-1', 'drawing-n-2', 'drawing-n-3', 'drawing-n-4', 'drawing-n-5', 'drawing-n-6', 'drawing-n-7', 'drawing-n-8', 'drawing-n-9', 'drawing-n-10', 'drawing-n-11', 'drawing-n-12', 'drawing-n-13', 'drawing-n-14', 'drawing-n-15', 'drawing-n-16', 'drawing-n-17']

key lambda只是解析在' - '标记后的每个字符串的最后一个找到的整数。

答案 2 :(得分:0)

如果格式与您的格式一致

,这将为您提供所需的内容

lambda x: int(x.split('-')[-1])