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.
Try creating a new list called newl
, then sort the lst
list by how many times the abs
olute 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]]