给定一个对的列表,如何按第二个值的频率对它们进行排序?

I am trying to sort a pair list such as [(1, 1), (2, 5), (2, 1), (3, 3), (5, 3)] by the frequency of the second term in each of the tuples. The resulting sorted list should be something like [(3,3),(5,3),(1,1),(2,1),(2,5)]. In this case, the frequency table would look like 1: 2, 3: 2, 5:1.

评论
  • xesse
    xesse 回复

    Using Counter to construct a key to pass to sort or sorted is a natural approach:

    from collections import Counter
    my_list = [(1, 1), (2, 5), (2, 1), (3, 3), (5, 3)]
    counts = Counter(y for _,y in my_list)
    sorted(my_list,key = lambda p:counts[p[1]],reverse = True)
    

    计算结果为:

    [(1, 1), (2, 1), (3, 3), (5, 3), (2, 5)]