Sort a sublist of elements in a list leaving the rest in place

前端 未结 15 2580
小蘑菇
小蘑菇 2021-02-13 14:28

Say I have a sorted list of strings as in:

[\'A\', \'B\' , \'B1\', \'B11\', \'B2\', \'B21\', \'B22\', \'C\', \'C1\', \'C11\', \'C2\']

Now I wan

15条回答
  •  耶瑟儿~
    2021-02-13 15:03

    If I'm understanding your question clear, you are trying to sort an array by two attributes; the alphabet and the trailing 'number'.

    You could just do something like

    data = ['A', 'B' , 'B1', 'B11', 'B2', 'B21', 'B22', 'C', 'C1', 'C11', 'C2']
    data.sort(key=lambda elem: (elem[0], int(elem[1:]))
    

    but since this would throw an exception for elements without a number trailing them, we can go ahead and just make a function (we shouldn't be using lambda anyways!)

    def sortKey(elem):
         try:
                 attribute = (elem[0], int(elem[1:]))
         except:
                 attribute = (elem[0], 0)
    
         return attribute
    

    With this sorting key function made, we can sort the element in place by

    data.sort(key=sortKey)
    

    Also, you could just go ahead and adjust the sortKey function to give priority to certain alphabets if you wanted to.

提交回复
热议问题