6

I have a list with sublists as follows:

result = [ ['helo', 10], ['bye', 50], ['yeah', 5], ['candy',30] ]

I want to sort this with three conditions: first, by highrest integer in index 2 of sublist, then by length of word in index 1 of sublist, and finally by alphabetical order in the 1st index of sublist.

I tried to do the following but it does not work:

finalresult = sorted(result, key=lambda word: (-word[1], len(word), word[0]))

This sorts it by the highest integer and alphabet order but not by length of word.

Any help is appreciated. Thank You.

1
  • When trying to debug bits like this promoting the lambda to a named function can make it much easier to see the issue. Lambdas are concise but they are not the most readable construct. Commented Oct 4, 2013 at 14:02

1 Answer 1

12

every element is a list of 2 elements, sorting by the length of the list is useless because all of them has the same length, maybe you want to sort by the length of the first element so

finalresult = sorted(result, key=lambda word: (-word[1], len(word[0]), word[0]))
Sign up to request clarification or add additional context in comments.

1 Comment

@HellMan you're welcome, if it solved the problem please consider to accept the answer ^^

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.