I have a list of
Sorted list : [(40, 8), (301, 8), (27, 147), (8, 181), (274, 181)]
I need to bring the coordinates that has same y coordinate in to a list like
[(40, 8), (301,8)]
[(8, 181), (274, 181)]
Can this be done?
I have a list of
Sorted list : [(40, 8), (301, 8), (27, 147), (8, 181), (274, 181)]
I need to bring the coordinates that has same y coordinate in to a list like
[(40, 8), (301,8)]
[(8, 181), (274, 181)]
Can this be done?
I suggest using a dictionary like so:
coordinate_list = [(40, 8), (301, 8), (27, 147), (8, 181), (274, 181)]
paired_lists = {}
for x, y in coordinate_list:
if y in paired_lists:
paired_lists[y].append((x, y))
else:
paired_lists[y] = [(x, y)]
Which gets me
print(paired_lists)
# {8: [(40, 8), (301, 8)],
# 147: [(27, 147)],
# 181: [(8, 181), (274, 181)]}
You can use itertools.groupby
for this job:
from itertools import groupby
lst = [(40, 8), (301, 8), (27, 147), (8, 181), (274, 181)]
for _, y in groupby(lst, lambda x: x[1]):
xs = list(y)
if len(xs) > 1:
print(xs)
# [(40, 8), (301, 8)]
# [(8, 181), (274, 181)]