Semi Unique Tuples in python? (so called primary keys?)

Using a list of tuples:

list = [(x,y,z),(x,y,z),(x,y,z)];

      

is there a Putin's way of enforcing uniqueness for only one index of a tuple?

Context: Tuples are albums. in the shape of:

(year, title, unique ID)

      

when the albums are re-released I get:

(2006, "White Pony", 3490349)
(2006, "White Pony", 9492423)
(2009, "White Pony", 4342342)

      

I don't care which one I hold, but only one can stay. how can I ensure that the middle element ([1]) is unique from any other tuple in the list?

+3


source to share


1 answer


my_list = [(2006, "White Pony", 3490349),(2006, "White Pony", 9492423),(2009, "White Pony", 4342342),(2006, "Red Pony", 3490349),(2006, "White Swan", 9492423),(2009, "White Swan", 4342342)]

seen = set() #< keep track of what we have seen as we go
unique_list = [x for x in my_list if not (x[1] in seen or seen.add(x[1]))]

print unique_list
# [(2006, 'White Pony', 3490349), (2006, 'Red Pony', 3490349), (2006, 'White Swan', 9492423)]

      



+3


source







All Articles