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

2024-04-26 05:56:17 发布

您现在位置: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])与列表中的任何其他元组都是唯一的?你知道吗


Tags: 方法id元素列表titlepythonicyear形式
1条回答
网友
1楼 · 发布于 2024-04-26 05:56:17
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)]

相关问题 更多 >