0

Ok, so I am trying for a long time to do this program. My question is can i sort a portion/slice of the list using the sorted command. Ok for more context the aim of my program is it inputs a list of tuples that are arbitrarily arranged and sorts it first by the second element then by the first. Say for eg. the list [(12, 2), (13, 4), (11, 1), (14, 2), (7, 2)] is passed; the function should first sort this into [(11, 1), (12, 2), (14, 2), (7, 2), (13, 4)] and then to [(11, 1), (7, 2), (12, 2), (14, 2), (13, 4)] the first parts easy but I am stuck in the second part. Here's what I tried:

def Sort(l):
    l = sorted(l, key=lambda l: l[1]) #for the first sort
    i = 0
    while i < len(l)-1:
        if l[i][1] == l[i+1][1]:
            z=i
            y = i +1
            print(z,i)
            while l[z][1] == l[z+1][1] and z < len(l)-1 and y<len(l) -1 :
                print(z)
                if l[z][0] > l[y][0]:
                    (l[z],l[z+1]) = (l[z+1],l[z])
                    print('if',l)
                y = y+1
                i= i+1
        i = i+1
    print(l)
    return l  

How do I go about achieving the second part! I am new to python!

jtagle
  • 302
  • 1
  • 8
Divakar
  • 19
  • 4
  • 1
    Thanks for showing us your homework; I'm sure this will become a ppcg soon. Try [/r/homeworkhelp](http://reddit.com/r/homeworkhelp) <3 – SIGSTACKFAULT Mar 06 '18 at 17:32
  • I'm sorry what is ppcg. Sorry if I asked something wrong and stupid @Blacksilver – Divakar Mar 06 '18 at 17:37
  • [Inside](https://codegolf.stackexchange.com/) [joke](https://xkcd.com/1960/) – SIGSTACKFAULT Mar 06 '18 at 17:38
  • Possible duplicate of [How to sort a list of lists by a specific index of the inner list?](https://stackoverflow.com/questions/4174941/how-to-sort-a-list-of-lists-by-a-specific-index-of-the-inner-list) – Mr. T Mar 06 '18 at 17:41

2 Answers2

3

Use itemgetter from the operator module.

from operator import itemgetter
keyfunc = itemgetter(1, 0) # sort by index 1, then index 0
sorted(l, key=keyfunc)
# [(11, 1), (7, 2), (12, 2), (14, 2), (13, 4)]
sytech
  • 29,298
  • 3
  • 45
  • 86
2

If I understand your logic correctly, you can do this in a single use of sorted:

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

>>> [(11, 1), (7, 2), (12, 2), (14, 2), (13, 4)]
sjw
  • 6,213
  • 2
  • 24
  • 39