how to sort list according to the number/another list

20221111

Sort with custom function using key

list.sort(key=len)
or
sorted(list, key=len)

# take second element for sort
def takeSecond(elem):
    return elem[1]

# random list
random = [(2, 2), (3, 4), (4, 1), (1, 3)]

# sort list with key
random.sort(key=takeSecond)

# print list
print('Sorted list:', random)

Sort with another list
[x for _, x in sorted(zip(Y, X))]

Reference:
[1] https://www.programiz.com/python-programming/methods/list/sort
[2] https://stackoverflow.com/questions/6618515/sorting-list-based-on-values-from-another-list

posted @ 2022-12-11 20:19  xiaoxuxli  阅读(11)  评论(0编辑  收藏  举报