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]]
?
Asked
Active
Viewed 283 times
-3

Paritosh Singh
- 6,034
- 2
- 14
- 33

user6148356
- 17
- 8
2 Answers
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