简体   繁体   中英

Sorting a list of list

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]]

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]]

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.

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]]

Try itemgetter

from operator import itemgetter
sorted(points, key=itemgetter(0, 1))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM