0

I have an output like this:

[['ca'], 0.62]
[['ca', 'tf'], 0.62]
[['ca', 'tf', 'se'], 0.71]
[['ca', 'tf', 'se', 'zz'], 0.71]
[['ca', 'tf', 'se', 'zz', 'rd'], 0.42]
[['ca', 'tf', 'se', 'zz', 'rd', 'fbs'], 0.12]
[['ca', 'tf', 'se', 'zz', 'rd', 'fbs', 'th'], 0.56]
[['ca', 'tf', 'se', 'zz', 'rd', 'fbs', 'th', 'ex'], 0.56]

The numbers in the right represent a score, I would like to sort them so I could have it that way:

[['ca', 'tf', 'se'], 0.71]
[['ca', 'tf', 'se', 'zz'], 0.71]
[['ca'], 0.62]
[['ca', 'tf'], 0.62]
[['ca', 'tf', 'se', 'zz', 'rd', 'fbs', 'th'], 0.56]
[['ca', 'tf', 'se', 'zz', 'rd', 'fbs', 'th', 'ex'], 0.56]
[['ca', 'tf', 'se', 'zz', 'rd'], 0.42]
[['ca', 'tf', 'se', 'zz', 'rd', 'fbs'], 0.12]

Higher score with less features first. I used this command:

li.sort(reverse=True)

but I got this error:

TypeError: '<' not supported between instances of 'list' and 'float'

Any idea how to do this properly ?

=====

Edit from Joe Ferndz

@DNZ, please consider this as your input:

li = [[['ca'], 0.62],
[['ca', 'tf'], 0.62],
[['ca', 'tf', 'se'], 0.71],
[['ca', 'tf', 'se', 'zz'], 0.71],
[['ca', 'tf', 'se', 'zz', 'rd'], 0.42],
[['ca', 'tf', 'se', 'zz', 'rd', 'fbs'], 0.12],
[['ca', 'tf', 'se', 'zz', 'rd', 'fbs', 'th'], 0.56],
[['ca', 'tf', 'se', 'zz', 'rd', 'fbs', 'th', 'ex'], 0.56]]

And the solution for this has already been posted by @Ali Shanoon. That should solve for it.

9
  • 3
    Based on the error message, it looks like you're trying to sort the list [['ca'], 0.62]. Are you sure you're sorting the list of scores, not just the first highscore? Commented Feb 19, 2021 at 21:08
  • Adding to that, it looks like the code in your first block is equivalent to li = [['ca'], 0.62]. Commented Feb 19, 2021 at 21:10
  • 2
    Are you sure li is defined correctly? Are you missing commas at the end of [['ca'], 0.62] Commented Feb 19, 2021 at 21:10
  • @SilvioMayolo What I want basically is just the first high score, I was trying to sort the lists reversely so I could select just the first high score. Commented Feb 19, 2021 at 21:11
  • 2
    @DNZ, i am not talking about the output. I am talking about the input. I think it is missing a comma and also missing a [] at the outside. Commented Feb 19, 2021 at 21:13

1 Answer 1

2

You were close. Sorted can take a key.

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

Comments

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.