从列表中删除对某些项目重复的列表 [英] Removing the lists from a list which are duplicated for some items

查看:63
本文介绍了从列表中删除对某些项目重复的列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从具有相同第一项和第三项但仅保留第一项的列表中删除这些列表.示例列表和输出:

I'm trying to remove the lists from a list which have same first and third items but only keeping the first one. Example list and output:

li=[ [2,4,5], [1,3,5], [1,6,5] ]
output_list = [ [2,4,5], [1,3,5] ]

我编写的代码要花很长时间才能执行,因为原始列表包含数百万个列表.

The code I've written takes a very long time to execute as the original list contains millions of list.

b_li = []
output_list = []
for x in li:
    s = [ x[0], x[2] ]
    if s not in b_li:
        b_li.append(s)
        output_list.append(x)

如何改进代码?预先感谢.

How can I improve the code? Thanks in advance.

推荐答案

改进的版本:

b_li = set()
output_list = []
b_li_add = b_li.add
output_list_append = output_list.append
for x in li:
    s = (x[0], x[2])
    if s not in b_li:
        b_li_add(s)
        output_list_append(x)

更改为:

  • b_li使用set()可以使查找更快.
  • s转换为元组,因为不需要将唯一的第一和第三元素存储为列表.
  • 减少的函数查找也可以加快代码的速度.
  • Use a set() for b_li which makes lookups faster.
  • Turn s into a tuple as there is no need to store unique first and third elements as lists.
  • Reduced function lookups which speeds up the code as well.

这篇关于从列表中删除对某些项目重复的列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆