Using a list of tuples:
list = [(x,y,z),(x,y,z),(x,y,z)];
is there a pythonic way to ensure uniqueness on only one tuple index?
context: the tuples are albums. in the form:
(year, title, unique ID)
when albums get rereleased, i'll end up with:
(2006, "White Pony", 3490349)
(2006, "White Pony", 9492423)
(2009, "White Pony", 4342342)
I don't care which one i keep, but only one can stay. how can I ensure the middle element ([1]) is unique from any other tuple in the list?
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)]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With