Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting a python list by frequency of their absolute difference

I have a list like,

lst=[[3,7],[4,9],[8,3],[1,5],[9,4],[4,5],[3,0],[2,7],[1,9]] 

And then want to sort this list by the frequency of their absolute difference like below:

|3-7|=4,  |4-9|=5,    |8-3|=5,    |1-5|=4,    |9-4|=5,    |4-5|=1,    |3-0|=3,    |2-7|=5,    |1-9|=8, 

Out put should be:

[[4,9],[8,3],[9,4],[2,7],[3,7],[1,5],[4,5],[3,0],[1,9]]

I am doing:

list.sort(key=self.SortByDifference,reverse=True)

def SortByDifference(self, element):
    return abs(element[0]-element[1])

But, this return highest difference first.

I would like to sort by the frequency of the absolute difference, so instead of sorting by the highest difference, i.e. [5, 5, 4, 4, 4, 3, 2, 1], it would output [4, 4, 4, 5, 5, 3, 2, 1] because 4 appears more often.

like image 463
Mohiuddin Avatar asked Jun 14 '26 10:06

Mohiuddin


1 Answers

Try creating a new list called newl, then sort the lst list by how many times the absolute difference appears in the newl:

lst=[[3,7],[4,9],[8,3],[1,5],[9,4],[4,5],[3,0],[2,7],[1,9]]
newl = [abs(x - y) for x, y in lst]
print(sorted(lst, key=lambda x: -newl.count(abs(x[0] - x[1]))))

Output:

[[4, 9], [8, 3], [9, 4], [2, 7], [3, 7], [1, 5], [4, 5], [3, 0], [1, 9]]
like image 59
U12-Forward Avatar answered Jun 15 '26 22:06

U12-Forward



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!