Data loss when sorting points
Question:
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.
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.
Answers:
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)]]
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.
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.
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)]]