Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
349 views
in Technique[技术] by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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]]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...