-3

So if I have this list [['a', 0.1], ['b', 0.05], ['c', 1.5]]. How does one order it by the second value so that the ordered list looks like this [['b', 0.05], ['a', 0.1], ['c', 1.5]]?

Paritosh Singh
  • 5,814
  • 2
  • 12
  • 31

2 Answers2

1
from operator import itemgetter
list  = [['a', 0.1], ['b', 0.05], ['c', 1.5], ['d', 0.2]]
a = sorted(list, key=itemgetter(1))
print(list)
print(a)
Xenobiologist
  • 2,011
  • 1
  • 11
  • 15
1

You can use sorted and tell it to use the second element:

a = [['a', 0.1], ['b', 0.05], ['c', 1.5]]
print(sorted(a, key=lambda k: k[1]))

key=lambda k: k[1] tells it take the second element (k[1]) and sort based on those values.

Lomtrur
  • 1,627
  • 1
  • 17
  • 31