I have a list of points that I need to sort in a zig/zag pattern,
I can easily sort by x+, y+
s = sorted(points, key=lambda tup: tup[1])
print(sorted(s))
points =
(73.76, 17.5495)
(72.635, 17.5495)
(72.635, 13.0495)
(73.76, 13.0495)
(73.76, -4.9505)
(73.76, -0.4505)
(72.635, -0.4505)
(72.6975, -4.9505)
(-72.635, -0.4505)
(-73.76, -0.4505)
(-73.76, -4.9505)
(-72.635, -4.9505)
(-72.635, 17.5495)
(-73.76, 17.5495)
(-73.76, 13.0495)
(-72.635, 13.0495)
(-75.75, -29.2532)
(-75.75, -32.2532)
(-69.75, -32.2532)
(-69.75, -29.2532)
(75.75, -32.2532)
(75.75, -29.2532)
(69.75, -29.2532)
(69.75, -32.2532)
(-54.25, -27.3195)
(-38.25, -27.3195)
(-38.25, -31.8195)
(-54.25, -31.8195)
(54.25, -31.8195)
(38.25, -31.8195)
(38.25, -27.3195)
(54.25, -27.3195)
(-79.5, 17.0)
(-77.0, 17.0)
(-77.0, 7.0)
(-79.5, 7.0)
(79.5, 17.0)
(77.0, 17.0)
(77.0, 7.0)
(79.5, 7.0)
result:
[(-79.5, 7.0), (-79.5, 17.0), (-77.0, 7.0), (-77.0, 17.0), (-75.75, -32.2532), (-75.75, -29.2532), (-73.76, -4.9505), (-73.76, -0.4505), (-73.76, 13.0495), (-73.76, 17.5495), (-72.635, -4.9505), (-72.635, -0.4505), (-72.635, 13.0495), (-72.635, 17.5495), (-69.75, -32.2532), (-69.75, -29.2532), (-54.25, -31.8195), (-54.25, -27.3195), (-38.25, -31.8195), (-38.25, -27.3195), (38.25, -31.8195), (38.25, -27.3195), (54.25, -31.8195), (54.25, -27.3195), (69.75, -32.2532), (69.75, -29.2532), (72.635, -0.4505), (72.635, 13.0495), (72.635, 17.5495), (72.6975, -4.9505), (73.76, -4.9505), (73.76, -0.4505), (73.76, 13.0495), (73.76, 17.5495), (75.75, -32.2532), (75.75, -29.2532), (77.0, 7.0), (77.0, 17.0), (79.5, 7.0), (79.5, 17.0)]
but this is not efficient for traveling between points - How could it be sorted so the second value is sorted in reverse for every other unique first value? what I can do, but not what I need -
What I am looking to achieve
First I store the unique "left values" using a set
, then I iterate over them and I sort each sub-list li
, altnerning the reverse
parameter with the variable rev
. In the final_list
, you get a "zig zag" sorting
points = [(1, 2), (1, 5), (3, 1), (3, 3), (2, 4), (2, 2)]
values = sorted(list(set(map(lambda x:x[0], points))))
# [1, 2, 3]
final_list = []
rev = False
for v in values:
li = [x for x in points if x[0] == v]
final_list += sorted(li, key=lambda tup: tup[1], reverse = rev)
rev = not rev
print(final_list)
# [(1, 2), (1, 5), (2, 4), (2, 2), (3, 1), (3, 3)]
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.