-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
  • 6,034
  • 2
  • 14
  • 33

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,091
  • 1
  • 12
  • 16
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,703
  • 2
  • 19
  • 35