I’ve searched around for pointers on this question but couldn’t find any. Suppose I have a list in Python:
list = set([((3, 2), (2, 1)),
((3, 2), (3, 1)),
((3, 1), (2, 1)),
((2, 1), (1,3), (2, 3))])
I want to refine this list so that entries of the list containing pairs with the same first element are thrown out. So for example, the output for the list above should be
set([((3, 2), (2, 1)),
((3, 1), (2, 1))])
Because ((3, 2), (3, 1)) and ((2, 1), (1,3), (2, 3)) are elements in which at least two of the coordinate pairs have the same first entry. Is there a fast and easy way to do this?
As it stands, I am thinking of doing something like
[x for x in list if ... ]
where I loop over the list by fixing x[k][0] and going through and comparing each x[i][0] with varying i to x[k][0], then looping over all such k‘s. I feel there has to be a better way to do this. Hope I was clear enough in this question, and I greatly appreciate your help.
This can be done quite easily with a simple set comprehension and a simple function:
Producing:
We take each item if the first element of each pair in the item is unique. We use the simple
no_duplicates()function (pulled from this great answer) to do this, which does what it says on the tin.