Sorting using a helper function?

前端 未结 2 1255
悲&欢浪女
悲&欢浪女 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: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]

提交回复
热议问题