Skip to main content
 首页 » 编程设计

python之根据每个子列表中的第三项删除列表列表中的重复项

2025年05月04日14qq号

我有一个列表列表,如下所示:

c = [['470', '4189.0', 'asdfgw', 'fds'], 
     ['470', '4189.0', 'qwer', 'fds'], 
     ['470', '4189.0', 'qwer', 'dsfs fdv']  
      ...] 

c 有大约 30,000 个内部列表。我想做的是根据每个内部列表中的第 4 项消除重复项。所以上面的列表列表看起来像:

c = [['470', '4189.0', 'asdfgw', 'fds'],['470', '4189.0', 'qwer', 'dsfs fdv'] ...] 

这是我目前所拥有的:

d = [] #list that will contain condensed c 
d.append(c[0]) #append first element, so I can compare lists 
for bact in c: #c is my list of lists with 30,000 interior list 
    for items in d: 
        if bact[3] != items[3]: 
            d.append(bact)   

我认为这应该可行,但它只是运行和运行。我让它运行 30 分钟,然后终止它。我不认为这个程序应该花这么长时间,所以我猜我的逻辑有问题。

我觉得创建一个全新的列表列表是非常愚蠢的。任何帮助将不胜感激,在我学习的过程中请随意挑剔。如果我的词汇不正确,请纠正我的词汇。

请您参考如下方法:

我会这样做:

seen = set() 
cond = [x for x in c if x[3] not in seen and not seen.add(x[3])] 

解释:

seen 是一个集合,它跟踪每个子列表中已经遇到的第四个元素。 cond 是压缩列表。如果 x[3](其中 x 是 c 中的子列表)不在 seen 中,x 将添加到 cond,x[3] 将添加到 seen。

seen.add(x[3]) 将返回 None,因此 not seen.add(x[3]) 将始终为 True,但只有当 x[3] not in seen 为 True 时才会评估该部分,因为 Python 使用短路评估。如果第二个条件得到评估,它将始终返回 True 并具有将 x[3] 添加到 seen 的副作用。这是正在发生的事情的另一个示例(print 返回 None 并具有打印某些内容的“副作用”):

>>> False and not print('hi') 
False 
>>> True and not print('hi') 
hi 
True