-1

first of all, i'm not English native speaker. so my sentences may be wired. please understand me!

Anyway, while I do my homework, i have to re-order the list nested with tuple by asc/desc order. my list is like this:

lst=[(a,30),(b,80),(c,180),(d,200),(e,90),(f,1200),(g,120),(h,920),(i,7)]

and i want to make that list to like this:

desc_lst=[(f,1200),(h,920),(d,200),(c,180),(g,120),(e,90),(b,80),(a,30),(i,7)]

and

asc_list=[(i,7),(a,30),(b,80),(e,90),(g,120),(c,180),(d,200),(h,920),(f,1200)].

how can i sort this? i can sort just normal list, for example lst=[1,2,3,4,9,8,5]. but in this case,i can't sort these because the list has tuple as an element. please answer...! ipy bless you and your family!

Ahsanul Haque
  • 10,676
  • 4
  • 41
  • 57
user6442076
  • 1
  • 1
  • 3

1 Answers1

1

Something like this should work

lst = [('a', 30), ('b', 80), ('c', 180), ('d', 200), ('e', 90), ('f', 1200), ('g', 120), ('h', 920), ('i', 7)]
print(sorted(lst, key=lambda x: x[1], reverse=True))

With the output result being

[('f', 1200), ('h', 920), ('d', 200), ('c', 180), ('g', 120), ('e', 90), ('b', 80), ('a', 30), ('i', 7)]
davidejones
  • 1,869
  • 1
  • 16
  • 18