Let's consider a list of tuples generated randomly:
>>> import random>>> l = [(random.randint(0, 100),random.randint(0, 100)) for i in range(10)]>>> l[(69, 38), (92, 75), (37, 89), (64, 52), (70, 72), (84, 44), (13, 0), (20, 67), (38, 56), (40, 98)]
to sort the list by the first tuple element, a solution is to use sorted():
>>> sorted(l)[(13, 0), (20, 67), (37, 89), (38, 56), (40, 98), (64, 52), (69, 38), (70, 72), (84, 44), (92, 75)]
or same
>>> sorted(l, key=lambda x: x[0])[(13, 0), (20, 67), (37, 89), (38, 56), (40, 98), (64, 52), (69, 38), (70, 72), (84, 44), (92, 75)]
to sort the list by the second tuple element
>>> sorted(l, key=lambda x: x[1])[(13, 0), (69, 38), (84, 44), (64, 52), (38, 56), (20, 67), (70, 72), (92, 75), (37, 89), (40, 98)]
Note: work also with sort(), except that sort change the original list l:
>>> l.sort(key=lambda x: x[0])>>> l[(13, 0), (20, 67), (37, 89), (38, 56), (40, 98), (64, 52), (69, 38), (70, 72), (84, 44), (92, 75)]>>> l.sort(key=lambda x: x[1])>>> l[(13, 0), (69, 38), (84, 44), (64, 52), (38, 56), (20, 67), (70, 72), (92, 75), (37, 89), (40, 98)]
References
| Links | Site |
|---|---|
| Sort a list of tuples by 2nd item (integer value) | stackoverflow |
| sort() | python doc |
| sorted() | python doc |
| Sorting HOW TO | python 3 doc |
| Python List sort() | programiz.com |
| sorted | Python doc |
| Python - how to sort a list of numerical values in ascending order | stackoverflow |
| How can I create a list of randomly generated tuples? | daniweb.com |
| Un exemple 1D de code python sur la méthode des k plus proches voisins | science-emergence |
| How to sort a list of numbers (in ascending or descending order) with python 3 ? | science-emergence |
