0

Current List:[['Magneto', 0, 'Insignificantly Evil'], ['Mystique', 0, 'Insignificantly Evil'], ['Mr. Sinister', 2, 'Cautiously Evil']]

I have the code above: I can sort it in order by the 2nd Column of the list, BUT I need HELP with sorting it by the first column if the second Column is the same. So the correct order of the list above is.

This list should be sorted first on the number (highest to lowest) with ties broken by the first column(lexicographical).

Final List:

[
  ('Mr. Sinister', 2, 'Cautiously Evil'),
  ('Magneto', 0, 'Insignificantly Evil'),
  ('Mystique', 0, 'Insignificantly Evil')
])

!Notice how only part of the first column has been sorted alphabetically, as first one is 2 so it get priority!

Please give ideas in anyway shape or form.

Gabriel Belini
  • 760
  • 1
  • 13
  • 32
Roger Tan
  • 41
  • 1
  • 6
  • You would use a comparator function https://stackoverflow.com/questions/12749398/using-a-comparator-function-to-sort – Teo Aug 11 '17 at 14:33
  • You might want to make it clear which column is author – bendl Aug 11 '17 at 14:35
  • Yes i've found the two sections of the list but i'm trying to sort just those two sections not everything else. Is that even possible? – Roger Tan Aug 11 '17 at 14:35
  • See these links as well. I think you're looking for `key=`.... https://wiki.python.org/moin/HowTo/Sorting#Key_Functions and https://stackoverflow.com/questions/8966538/syntax-behind-sortedkey-lambda – bendl Aug 11 '17 at 14:37
  • HI yes thanks for showing these links but they don't show how you can sort a section of a list in a section of lists of lists. – Roger Tan Aug 11 '17 at 14:39

1 Answers1

0

I think you will need to convert this to list because you use python 3.x, but this will work:

a = [['Magneto', 0, 'Insignificantly Evil'], ['Mystique', 0, 'Insignificantly Evil'], ['Mr. Sinister', 2, 'Cautiously Evil']]
sorted(a, key=lambda x: (-x[1], x[0]))
#[['Mr. Sinister', 2, 'Cautiously Evil'],
# ['Magneto', 0, 'Insignificantly Evil'],
# ['Mystique', 0, 'Insignificantly Evil']]

lambda is an anonymous function that takes parameter x and returns tuple with negative 2nd element and 1st element as it is.

Sorting will be by first and then by second element of returned tuple.

Default sorting is ascending so the negatives will go first.

zipa
  • 27,316
  • 6
  • 40
  • 58