0

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?

  • Possible duplicate of [How to sort (list/tuple) of lists/tuples?](https://stackoverflow.com/questions/3121979/how-to-sort-list-tuple-of-lists-tuples) – Remy Feb 10 '19 at 07:53
  • Pure code-writing requests are off-topic on Stack Overflow — we expect questions here to relate to *specific* programming problems — but we will happily help you write it yourself! Tell us [what you've tried](https://stackoverflow.com/help/how-to-ask), and where you are stuck. This will also help us answer your question better. – Jeff Woodard Feb 10 '19 at 09:30

2 Answers2

0

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)]}
Aule Mahal
  • 688
  • 5
  • 10
  • Thank you for your suggestion.The method that you suggest is working.but the problem is it is returning only one pair. But there are two pairs whose y values are same. Can you suggest how to fix this? – Asna Aleem Feb 10 '19 at 06:31
  • I'm not sure what you mean? I edited my answer to show what result it gives when run on your example list. You can iterate on `paired_lists.values()` to get only the coordinates. – Aule Mahal Feb 10 '19 at 19:02
0

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)]
Austin
  • 25,759
  • 4
  • 25
  • 48