使用元组列表:
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])与列表中的任何其他元组都是唯一的?
答案 0 :(得分:4)
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)]