Sorting using a helper function?

前端 未结 2 1252
悲&欢浪女
悲&欢浪女 2021-01-28 11:28

I have two variables: numbers = [8, 3, 1, 2, 5, 4, 7, 6] and group = [2, 3, 5, 7]. The group variable are the numbers that should be first

相关标签:
2条回答
  • 2021-01-28 11:36

    Duples are sorted in order:

    (0, 10) < (0, 50) < (1, 10) < (1, 50)
    

    By using key=helper, it uses the helper function to transform the input while sorting. helper takes the regular number (say, 7) and then wraps it up in a tuple that indicates whether it's in group (in this case (0, 7)). Then when there's a number that's no in group, it'll be forced to appear afterwards ((1, 6), for example).

    0 讨论(0)
  • 2021-01-28 11:57

    While @tsm has answered the question, it's worth looking at a simpler example that achieves the same effect. This example assumes that all the ints in the numbers list are less than 100 (so the original code is better, but I'm offering this simpler example just to try and make things clearer).

    Basically what this example does is to add 100 to any number that is not in the group list - that gives non-group numbers a higher sort value. So, a number X that is in the group has a sort order of X, while a number Y that is not in the group has a sort order of 100+Y.

    numbers = [8, 3, 1, 2, 5, 4, 7, 6]
    group = [2, 3, 5, 7]
    
    def sort_priority(values, group):
        def helper(x):
            if x in group:
                return x
            else:
                return 100 + x
        values.sort(key=helper)
    
    print("Before:", numbers)
    sort_priority(numbers, group)
    print("After: ", numbers)
    

    So, the number list to be sorted is: [8, 3, 1, 2, 5, 4, 7, 6]

    But the sort is based on a second, transformed list: [100+8, 3, 100+1, 2, 5, 100+4, 7, 100+6]

    0 讨论(0)
提交回复
热议问题