-3

How can I sort a list in order? I have a list of tuples in a list and I need to sort them in order which I want.

list1 = [(2,3,4),(3,4,5),(5,3,2)]

I need to sort them firstly by the second element of tuple, secondly(if the previous were equal) by the third and thirdly by the first. Is there any built-in function to do it?

Ch3steR
  • 20,090
  • 4
  • 28
  • 58
Mahdi Amrollahi
  • 2,930
  • 5
  • 27
  • 37
  • 1
    There's a built-in [`sorted` function](https://docs.python.org/3/library/functions.html#sorted), yes. Did you look it up? What have you tried, and what exactly is the problem with it? – jonrsharpe Mar 01 '20 at 18:47
  • I need the "order sort" like what we have in Excel. What will you do, if you want to sort the list in order you need? As an example, sort by the second column, then third column and then first column. – Mahdi Amrollahi Mar 01 '20 at 18:52
  • Did you read the docs on that function? The how-to it links to? What's what I'd do. – jonrsharpe Mar 01 '20 at 18:54

1 Answers1

2

You can use sorted(iterable,key).

>>>sorted(list1,key=lambda x: (x[1],x[2],x[0])
#[(5, 3, 2), (2, 3, 4), (3, 4, 5)]

If you don't want to use lambda you can use itemgetter.

from operator import itemgetter
sorted(list1,key=itemgetter(1,2,0))
#[(5, 3, 2), (2, 3, 4), (3, 4, 5)]
Ch3steR
  • 20,090
  • 4
  • 28
  • 58
  • Can I use ascending and descending in each element I need? Or I should choose one of them for all. – Mahdi Amrollahi Mar 01 '20 at 19:56
  • @MehdiAmrollahi `lambda x: (x[1],x[2],x[0])` this means they are sorted bases *2nd* if they are equal then *3rd* element is compared is break the tie, if they too are equal then *1st* element is used as tie breaker. – Ch3steR Mar 01 '20 at 19:59