简体   繁体   中英

What's the meaning of (0,x) and (1,x) in this code?

This code is used to sort a big_list but put the small_list in the beginning of the big_list. I don't understand how the argument 'x' is passed to the def helper and what's the meaning of return (0,x) and (1,x) here. Any help would be greatly appreciated.

def sort_list(value, group):
    def helper(x):
        if x in group:
            return (0,x)
        return (1,x)
    value.sort(key=helper)
big_list = [8,3,1,2,5,4,7,6]
small_list = [2,3,5,7]
sort_list(big_list, small_list)
print(big_list)
[2, 3, 5, 7, 1, 4, 6, 8]

(0,x) is a two-member tuple. The key insight is that tuples sort by first element, disambiguating by second element, then next.... and only being equal when each member is equal. Thus, for example,

(0, 0) < (0, 1) < (0, 2) < (1, 0) < (1, 1) < (1, 2)

Thus, helper as the sort key will sort any elements in group before any elements outside group ; but then sort by value inside each part. This accounts for 2, 3, 5, 7 being ordered, 1, 4, 6, 8 being ordered, and the former coming before the latter.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM