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

标签 python duplicates nested-lists

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

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](其中 xc 中的子列表)不在 seen 中,x 将添加到 condx[3] 将添加到 seen

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

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

关于python - 根据每个子列表中的第三项删除列表列表中的重复项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24295578/

相关文章:

python - 从彼此中减去两个元组列表

Python 无法验证 SSL/TLS 连接的任何 CRL

mysql - 防止MySQL中的重复输入(例如,当快速调用多次插入请求时)

mysql - 具有唯一键约束的数据库中的重复行

java - 使用 O(1) 空间从数组列表中删除非唯一数字

pdf - 如何使用 iText 将 XHTML 嵌套列表转换为 pdf?

python - 公历日期-numDays 函数

python - Typehint 使用 importlib 动态导入模块

sencha-touch - Sencha Touch 1 的嵌套列表无限循环

php - 如何在 PHP 中重新排序嵌套元素?