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

How to split a list based on tuple content in Python

I have a list of 3-tuples, and I want to split them on the last coordinate. So for example if the input were:

[(1,2,x), (2,3,x), (1,2,z), (2,20,z)]

I’d want the output to be

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

[(1,2,x),(2,3,x)],[(1,2,z),(2,20,z)]

My current approach involves getting all N distinct 3rd indices and looping over the list N times to build the list of lists. I am wondering if there is a pythonic way to do this without looping multiple times.

>Solution :

here is one way with complexity of O(n):

lt = [(1,2,'x'), (2,3,'x'), (1,2,'z'), (2,20,'z')]

res = {}
for i in lt:
  res.setdefault(i[2], []).append(i)

print(list(res.values()))

output:

>>>
[[(1, 2, 'x'), (2, 3, 'x')], [(1, 2, 'z'), (2, 20, 'z')]]
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