Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Semi Unique tuples in python? (aka. tuple primary keys?)

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?

like image 965
deadPix3l Avatar asked May 31 '26 00:05

deadPix3l


1 Answers

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)]
like image 160
Joran Beasley Avatar answered Jun 01 '26 15:06

Joran Beasley



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!