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.

Joe Ferndz
  • 8,417
  • 2
  • 13
  • 33
DNZ
  • 37
  • 5

1 Answers1

2

You were close. Sorted can take a key.

sorted(li, reverse=True, key=lambda x: (x[-1], -len(x[0])))
Ali Shannon
  • 186
  • 3