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
[(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')]]