2

So I have a list like below:

points = [[0, 0], [5, 3], [0, 5], [0, 2], [1, 3], [5, 3]]

I have been using

points.sort(key=lambda pair: pair[0])

to sort the list. But this only sorts it by first value without looking at the second value.

The result of this code is as below:

[[0, 0], [0, 5], [0, 2], [1, 3], [5, 3], [5, 3]]

However, I want to sort is such that the result is:

[[0, 0], [0, 2], [0, 5], [1, 3], [5, 3], [5, 3]]

How do I do it?

Also, while we are at it, how do i remove the duplicates from this list? The final result should be like:

[[0, 0], [0, 2], [0, 5], [1, 3], [5, 3]]
Sangam Belose
  • 4,262
  • 8
  • 26
  • 48
nnut
  • 35
  • 7

4 Answers4

5

Python already sorts iterable containers (tuples, lists, ...) and strings lexicographically.

>>> points = [[0, 0], [5, 3], [0, 5], [0, 2], [1, 3], [5, 3]]
>>> sorted(points)
[[0, 0], [0, 2], [0, 5], [1, 3], [5, 3], [5, 3]]
timgeb
  • 76,762
  • 20
  • 123
  • 145
  • @NutanNepal not at all, see [my first question](https://stackoverflow.com/questions/20145842/python-sorting-by-multiple-criteria). I didn't get lexicographical sorting either. – timgeb Jan 09 '18 at 06:47
1

You can have a sort key that first sorts by the first element x[0], and if their are ties, sort by the second element x[1]:

>>> points = [[0, 0], [5, 3], [0, 5], [0, 2], [1, 3], [5, 3], [0, 4]]
>>> sorted(points, key = lambda x: (x[0], x[1]))
[[0, 0], [0, 2], [0, 4], [0, 5], [1, 3], [5, 3], [5, 3]]

If you don't want any duplicates in this final list, then you can do this:

points = [[0, 0], [5, 3], [0, 5], [0, 2], [1, 3], [5, 3]]

sorted_lst = sorted(points, key = lambda x: (x[0], x[1]))

seen = set()
no_dups = []
for lst in sorted_lst:
    curr = tuple(lst)
    if curr not in seen:
        no_dups.append(lst)
        seen.add(curr)

print(no_dups)
# [[0, 0], [0, 2], [0, 5], [1, 3], [5, 3]]

Which has a set seen which keeps track of what sublists have been added, and a list no_dups where the lists get added. If an element is not in seen and add it to the final list, and add it to seen, which indicates that the element has already been added.

Also since type list is not a hashable type, you cannot add them directly to a set. In the above code, the lists are converted to tuples and added to seen, which is a hashable type.

RoadRunner
  • 25,803
  • 6
  • 42
  • 75
1
import itertools

points = [[0, 0], [5, 3], [0, 5], [0, 2], [1, 3], [5, 3]]
points.sort()
nList = list(points for points,_ in itertools.groupby(points))
print nList

Result:

[[0, 0], [0, 2], [0, 5], [1, 3], [5, 3]]
Rakesh
  • 81,458
  • 17
  • 76
  • 113
0

Try itemgetter

from operator import itemgetter
sorted(points, key=itemgetter(0, 1))
Ernest S Kirubakaran
  • 1,524
  • 12
  • 16