-4

I apologize of if this is a duplicate of this.

Sort a list of tuples depending on two elements depending-on-two-elements

What I have is a unsorted list of tuples

unsorted_list  = [(50,45), (35,40)]
sorted_list = [(35,40), (50,45)]

I want to end up with the following sorted list. I tried the following:

sorted(unsorted, key=lambda element: (element[0], element[1]))

My result was the following, which is not what I wanted.

[(35, 40), (45,50)]
Kulwant
  • 641
  • 2
  • 11
  • 28
  • 5
    Your output appears to be what you said you wanted, so it's unclear what you're asking. – jonrsharpe Nov 16 '17 at 17:15
  • 1
    BTW, that particular key function is redundant: that's how two-element tuples will be sorted without a key function arg. – PM 2Ring Nov 16 '17 at 17:23
  • Sorry, I modified it to what I wanted. I want the numbers ordered throughout. Thanks! – Kulwant Nov 16 '17 at 17:32
  • I think you've got those outputs mixed up. You say that "I want the numbers ordered throughout", but in the question you say that your result was `[(35, 40), (45,50)]`, "which is not what I wanted". – PM 2Ring Nov 16 '17 at 17:43
  • Bear in mind that tuples are immutable, so you can't simply sort their contents. You have to create new tuples that contain the sorted items of the old tuples. – PM 2Ring Nov 16 '17 at 17:44

1 Answers1

0

Tuples are immutable, so you can't simply sort their contents. You have to create new tuples that contain the sorted items of the old tuples. Here's a simple way to do that with a list of two-item tuples.

unsorted_list = [(50,45), (35,40)]
sorted_list = [(min(t), max(t)) for t in sorted(unsorted_list)]
print(sorted_list)

output

[(35, 40), (45, 50)]

Another option is

sorted_list = [(u, v) if u<=v else (v, u) for u,v in sorted(unsorted_list)]
PM 2Ring
  • 54,345
  • 6
  • 82
  • 182