Ricky Robinson
Ricky Robinson

Reputation: 22933

Python: sort list of nested lists according to two criteria

In Python, I have a nested list like the following:

[ [[x1,y1,z1], [['0.9', 4], [0.8, 3], [0.5, 10], [0.1, 11]], 
  [[x2,y2,z2], [['1.0', 8], [0.8, 3], [0.2, 1], [0.1, 8]]
...]

So each element is in the form:

 [[3-tuple], [[val1, occurrences_of_val1], [val2, occurrences_of_val2],...]]

The second nested list is already sorted by the first item (val1 > val2 > val3 ...), but I want also the 3-tuples [x,y,z] to appear sorted in descending order according to two criteria:

  1. value of val1 (highest first)
  2. in case of same val1, highest occurrences_of_val1 (possibly applied to val2 if the two values above are the same)

How do I do this? Probably with itemgetter, but I'm not sure in this case.

Upvotes: 2

Views: 5395

Answers (2)

kiriloff
kiriloff

Reputation: 26333

I tested this

X=[ [[4,5,6], [[3.0, 4], [0.8, 3], [0.5, 10], [0.1, 11]]],
  [[2,1,3], [[2.0, 8], [0.8, 3], [0.2, 1], [0.1, 8]]]]
>>> X.sort(key=lambda x: x[1])
>>> X
[[[2, 1, 3], [[2.0, 8], [0.80000000000000004, 3], [0.20000000000000001, 1], [0.10000000000000001, 8]]], [[4, 5, 6], [[3.0, 4], [0.80000000000000004, 3], [0.5, 10], [0.10000000000000001, 11]]]]

Most importantly, X.sort(key=lambda x: x[1]) is sorting by second element of X, that is by this elements [[val1, occurrences_of_val1], [val2, occurrences_of_val2],...]. Implicitely, it is sorting by val1, then in case of equality by occurrences_of_val1 ...

Upvotes: 3

Steven Rumbalski
Steven Rumbalski

Reputation: 45562

yourList.sort(key=lambda x: x[1], reverse=True)

Upvotes: 7

Related Questions