python中的半唯一元组? (又名元组主键?)

使用元组列表:

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

有没有一种pythonic的方法来确保只有一个元组索引的唯一性?

上下文:
元组是专辑.形式:

(year, title, unique ID)

当专辑重新发行时,我将得到:

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

我不在乎我保留哪一个,但是只有一个可以留下.如何确保中间元素([1])与列表中的任何其他元组是唯一的?

解决方法:

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)]
上一篇:从Python中的元组列表中获取配对元素


下一篇:python-向元组添加元素的有效方法