Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Data loss when sorting points

After finding a large set of points I’m now trying to sort them such that:

arr = [(1,2)(1,3)(1,4)(2,1)(2,3)]

becomes:

[[(1,2)(1,3)(1,4)],[(2,1)(2,3)]]

In other words I’m trying to group the points by their x coordinate.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I wrote below function to do this:

def sortPoints(points):
    prev = NULL
    sorted = []
    groupe = []
    for p in points:
        if prev == NULL : prev = p[0]
        if p[0] == prev:
            groupe.append(p)
        else :
            sorted.append(groupe[:])
            del groupe[:]
            prev = p[0]
    return sorted

When I run the code I get an array with sorted points as expected, however, a large part of the points also vanish in the process, and I cannot figure out why.

If anyone could help me, that would be great and very appreciated. Thank you in advance.

>Solution :

As mark suggested you should use itertools.groupby for such cases

from itertools import groupby
arr = [(1,2),(1,3),(1,4),(2,1),(2,3)]
arr.sort(key=lambda x: x[0])
[list(v) for _,v in groupby(arr, lambda y: y[0])]
# output
[[(1, 2), (1, 3), (1, 4)], [(2, 1), (2, 3)]]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading