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
.
Asked
Active
Viewed 166 times
-4

RoadRunner
- 25,803
- 6
- 42
- 75

Krish
- 415
- 2
- 11
2 Answers
2
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)
Which evaluates to:
[(1, 1), (2, 1), (3, 3), (5, 3), (2, 5)]

John Coleman
- 51,337
- 7
- 54
- 119
0
Similar to @John's answer, we can build a frequency map using a collection.defaultdict
, then sort by the second value of each tuple using the frequencies from the dictionary, making sure we sort in reverse:
from collections import defaultdict
lst = [(1, 1), (2, 5), (2, 1), (3, 3), (5, 3)]
frequency_map = defaultdict(int)
for _, snd in lst:
frequency_map[snd] += 1
print(sorted(lst, key=lambda x: frequency_map[x[1]], reverse=True))
Output:
[(1, 1), (2, 1), (3, 3), (5, 3), (2, 5)]

RoadRunner
- 25,803
- 6
- 42
- 75