Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Sorting Q.
#1
Suppose I have a list of lists:
listA = [['A', 5], ['B', 18], ['C', 18], ['D', 34] 
I know how to use itemgetter to sort by the second element, the number, in reverse order. D 34, C 18, B 18, A 5 etc...

What if I want to make sure that in cases where 2 entries have the same number they are sorted alphabetically?

I want the numbers descending but the letters ascending. D 34, B 18, C 18, A 5 etc...

How do I do that please?
Reply
#2
>>> import operator
>>> s = sorted(listA, key = operator.itemgetter(1, 0))
>>> s
[['A', 5], ['B', 18], ['C', 18], ['D', 34]]
>>>
Scramble it up a bit to make sure it's working:
>>> listA = [['C', 18], ['D', 34], ['B', 18], ['A', 5]]
>>> s = sorted(listA, key = operator.itemgetter(1, 0))
>>> s
[['A', 5], ['B', 18], ['C', 18], ['D', 34]]
>>>
Reply
#3
(Mar-31-2018, 09:00 PM)Larz60+ Wrote:
>>> import operator
>>> s = sorted(listA, key = operator.itemgetter(1, 0))
>>> s
[['A', 5], ['B', 18], ['C', 18], ['D', 34]]
>>>
Scramble it up a bit to make sure it's working:
>>> listA = [['C', 18], ['D', 34], ['B', 18], ['A', 5]]
>>> s = sorted(listA, key = operator.itemgetter(1, 0))
>>> s
[['A', 5], ['B', 18], ['C', 18], ['D', 34]]
>>>
OK but what if I want the numbers reversed but the letters still in normal A-Z order in case of a tie?
Reply
#4
use reverse=True
s = sorted(listA, key = operator.itemgetter(1, 0), reverse=True)
Reply
#5
(Mar-31-2018, 09:19 PM)Larz60+ Wrote: use reverse=True
s = sorted(listA, key = operator.itemgetter(1, 0), reverse=True)

So the reverse is only applied to the primary sort?
EDIT:
Does not seem to be working.
rankByFreq = sorted(rankByFreq,key=itemgetter(1, 0), reverse = True)
    print (rankByFreq)
This is what I get back:
[['T', 39], ['P', 29], ['I', 26], ['H', 26], ['E', 26], ['D', 24], ['W', 23], ['X', 22], ['S', 20], ['L', 20], ['A', 18], ['G', 15], ['Y', 14], ['C', 14], ['R', 13], ['U', 11], ['M', 9], ['N', 6], ['J', 6], ['B', 6], ['V', 5], ['Q', 5], ['Z', 4], ['K', 3], ['O', 2], ['F', 1]]
I want it to go E H I not I H E etc...
Reply
#6
E H I is forward sort, not reversed!
Reply
#7
(Mar-31-2018, 11:34 PM)Larz60+ Wrote: E H I is forward sort, not reversed!

LOL Yes I know. What I want to do is reverse sort by number but in case of tie. It's OK now. I figured out I can sort it regular by the letter then sort it again reversed by the number.

Thanks for your help. Sorry if I stressed you out :D I can't always phrase my questions clearly.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Sorting a copied list is also sorting the original list ? SN_YAZER 3 3,310 Apr-11-2019, 05:10 PM
Last Post: SN_YAZER

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020