В качестве альтернативы вы можете использовать функцию itemgetter()
в качестве параметра key
для sorted()
функция:
from operator import itemgetter
points = [(7,3), (2,1), (4,5), (9,0)]
sorted_by_x = sorted(points) # you can add the key parameter itemgetter(0) if you want
sorted_by_y = sorted(points, key=itemgetter(1))
print("Points List: {}".format(points))
print("Sorted by X Points List: {}".format(sorted_by_x))
print("Sorted by Y Points List: {}".format(sorted_by_y))
Выход:
Points List: [(7, 3), (2, 1), (4, 5), (9, 0)]
Sorted by X Points List: [(2, 1), (4, 5), (7, 3), (9, 0)]
Sorted by Y Points List: [(9, 0), (2, 1), (7, 3), (4, 5)]