Python list custom order sorting

sortfunction is a very useful function that can sort the elements in a list. By default, sortthe function sorts the elements in ascending order, but sometimes we need a custom sorting of the list. In this case, we can keyimplement custom sorting using parameters and passing a custom sort function.

  • The sample code is as follows:

    def custom_sort(value, sort_list=[2,3,1,6,5]):
        """ 按照指定的顺序对返回数据排序 """
        custom_order = sort_list
        if value in custom_order:
            return custom_order.index(value)
        else:
            return len(custom_order)
    
    a = [6,5,4,3,2,1]
    a.sort(key=custom_sort)
    print(a)
    
  • In the sample code above, we defined a custom_sortfunction called to implement custom sorting.

  • custom_sortThe function takes two parameters: valueand sort_list. valueThe parameters represent the values ​​to be sorted, and sort_listthe parameters represent the specified sort order. If valuein sort_list, custom_sortthe function returns the index valuein sort_list. Otherwise, the function will return sort_listthe length.

  • Python's custom sorting functions are very useful. It can sort the list according to its own needs instead of the default ascending or descending order, allowing for better management and processing of data.

Guess you like

Origin blog.csdn.net/weixin_44649870/article/details/128957895