Reputation: 35
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]]
Upvotes: 2
Views: 95
Reputation: 26315
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.
Upvotes: 1
Reputation: 78650
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]]
Upvotes: 5
Reputation: 82755
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]]
Upvotes: 1
Reputation: 1564
Try itemgetter
from operator import itemgetter
sorted(points, key=itemgetter(0, 1))
Upvotes: 0