Home > Software design >  How do I solve it?
How do I solve it?

Time:11-18

I am currently trying to solve a problem involving lists and sorting (i.e.) when a list (not a normal one ,but a list of tuple ) is entered ; the program should print out the list but in an orderly(increasing order) manner based on the 2nd elements of each tuples. ex: Sample List : [(2, 5), (1, 2), (4, 4), (2, 3), (2, 1)] Expected Result : [(2, 1), (1, 2), (2, 3), (4, 4), (2, 5)] Here is what I have tried until now:

def sorting(L):
le=len(L)
G=[]
Lnew=[list(l) for l in L]
for i in range(le):
    G.append(Lnew[i][1])
    G.sort()
    Lnew.remove(Lnew[i][1]) #where the problem is
    for k in range(len(G)):
        Lnew[k][1]=G[k]
        for elt in Lnew:
            tuple(elt)
return L

An error displays "list.remove(x): x not in list" . how do I proceed in that case? or is there a simpler way to tackle the problem ?

CodePudding user response:

from operator import itemgetter
lista_of_tuples = sorted(list_of_tuples, key_itemgetter(0))

itemgetter parameter can be 0,1,2 depending which one to order it by

CodePudding user response:

def sorting(my_list):
    return sorted(my_list, key=lambda x: x[1])

sorting([(2, 5), (1, 2), (4, 4), (2, 3), (2, 1)])  

Output: [(2, 1), (1, 2), (2, 3), (4, 4), (2, 5)]
  • Related