1

I have this list structure:

[[[6], [4], 1.0], [[5, 6], [4], 1.0], [[5], [6], 1.0], [[5], [4, 6], 1.0], [[5], [4], 1.0], [[4, 5], [6], 1.0], [[4], [6], 0.8]]

And I want to sort it via the 3rd element (descending order) and the lengths of the first and second list (first the ones which are smaller). I tried using

r = sorted(r, key=itemgetter(2, 0, 1), reverse=True)

which sorts the 3rd element in descending order, but how can I add the other sorting restrictions to this one?

Expected output:

[[[6], [4], 1.0], [[5], [6], 1.0], [[5], [6], 1.0], [[5], [4], 1.0], [[5], [4, 6], 1.0], [[5, 6], [4], 1.0], [[4, 5], [6], 1.0], [[4], [6], 0.8]]
4
  • What is the expected output? Commented Nov 2, 2017 at 13:23
  • @DeepSpace I edited the question to show you the expected output. But basically as I said, I want it to be sorted first given the 3rd element, and then for the length of the first and second list (shortest first) Commented Nov 2, 2017 at 13:26
  • @JHBonarius yeah sorry, now it is corrected Commented Nov 2, 2017 at 13:27
  • @JHBonarius no its not a duplicate, I need 2 sorting restrictions in this case.. Commented Nov 2, 2017 at 13:28

2 Answers 2

2

Use a lambda expression:

r = sorted(r, key=lambda x:(x[2], -len(x[0]), -len(x[1])), reverse=True)

or sort without reassignment:

r.sort(key=lambda x:(x[2], -len(x[0]), -len(x[1])), reverse=True)
Sign up to request clarification or add additional context in comments.

1 Comment

Almost right. you need to inverse the size, because he wants the smallest first r.sort(key=lambda x:(x[2], -len(x[0]), -len(x[1])), reverse=True)
0

I don't believe you could do this in one line, you would need to do in stages like this, with the primary key last:

a = [[[6], [4], 1.0], [[5, 6], [4], 1.0], [[5], [6], 1.0], [[5], [4, 6], 1.0],
     [[5], [4], 1.0], [[4, 5], [6], 1.0], [[4], [6], 0.8]]
b = sorted(a, key=lambda x : len(x[1]), reverse=False)
c = sorted(b, key=lambda x : len(x[0]), reverse=False)
d = sorted(c, key=itemgetter(2), reverse=True)

This gives the correct result:

>>> d [[[6], [4], 1.0], [[5], [6], 1.0], [[5], [6], 1.0], [[5], [4], 1.0], [[5], [4, 6], 1.0], [[5, 6], [4], 1.0], [[4, 5], [6], 1.0], [[4], [6], 0.8]]

See the docs for more information.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.