-2

i have a list containing several tuples like this one:

(label, count)

and i want to sort them by theirs counts, but i have no idea how i can do that. I know python has a built-in function sort() but i don't think i can use it in my case. I hope someone know how to do this.

example:

input: [("label 1", 5), ("label 2", 1), ("label 3", 3), ("label 4", 6)]
output: [("label 4", 6), ("label 1", 5), ("label 3", 3), ("label 2", 1)]
Pedro Lobito
  • 94,083
  • 31
  • 258
  • 268
rémi couturier
  • 425
  • 3
  • 11

1 Answers1

-1
a = [("label 1", 5), ("label 2", 1), ("label 3", 3), ("label 4", 6)]
a = sorted(a, key = lambda x: int(x[1]), reverse = True)

a becomes

[('label 4', 6), ('label 1', 5), ('label 3', 3), ('label 2', 1)]
Kuldeep Singh Sidhu
  • 3,748
  • 2
  • 12
  • 22