0

so I have a list with tuples consisting out of a string with a value. I have sorted the list so the tuples are ordered with a descending order (from high to low). Now I want for the tuples with the same values that those tupples are sorted alphabetically. An example:

list = [(B,10),("A",10),("C",7),("E",5),("D",5)]

becomes

 list =[("A",10),("B",10),("C",7),("D",5),("E",5)]

Thank you in advance

TheCreator
  • 155
  • 6

2 Answers2

2

You can try this, assuming s is your list.. (list keyword is a saved keyword and not recommended to use as variable...):

s = sorted(s, key = lambda x: (-x[1], x[0]))

Note that your specific example can be just sorted by the first element, but to be more generic you can just use this sort for cases where it wont be enough for your expected result

adir abargil
  • 5,495
  • 3
  • 19
  • 29
  • Wow thank you so much, really appreciate it, sidenote where can I find the techniques you use because I'm not familiar with s, key = lambda x: (-x[1], x[0])? – TheCreator Dec 11 '20 at 12:50
  • You can pass the key as a function that return the pbject you want to sort by, if you return a tuple it goes from the first one to the second in case of equality.. i added - because it was a number but for more complex cases you can send another argument `cmp=` to make the comparison.. – adir abargil Dec 11 '20 at 13:18
0

Use the python built-in sorted() method.

sorted(list); #[('A', 10), ('B', 10), ('C', 7), ('D', 5), ('E', 5)]

Also as an important note, list is a reserved key-word, it would be better to use other names to prevent confusion, and potentially avoid errors later on.

  • thank you It did change the total order of my list (in my code not example), but stil thank you for helping really appreciate it. – TheCreator Dec 11 '20 at 12:51