python 列表去重(不可变类型和可变类型)

来源:互联网 发布:表达知错的句子 编辑:程序博客网 时间:2024/06/04 19:42

不可变类型

  • 利用set特性去重
ids = [1, 3, 8, 3, 8, 1, 9, 9, 9, 1]ids = list(set(ids))
  • 新建一个list,循环遍历
ids = [1, 3, 8, 3, 8, 1, 9, 9, 9, 1]new_ids = []for item in ids:    if item not in new_ids:        new_ids.append(item)
  • 使用reduce处理
ids = [1, 3, 8, 3, 8, 1, 9, 9, 9, 1]func = lambda x, y: x if y in x else x + [y]ids = reduce(func, [[], ] + ids)

可变类型

  • 用set处理
class A:    def __init__(self, no, name):        self.no = no        self.name = name    def __eq__(self, other):        return self.no == other.no and self.name == other.name    def __hash__(self):        return hash(self.no) ^ hash(self.name)    def __repr__(self):        return str(self.no)+":"+self.namea_list = [A(1, "a"), A(2, "a"), A(1, "a"), A(1, "b")]a_list = list(set(a_list))# a_list = [1:b, 2:a, 1:a]a_list.sort(key=lambda a: a.no)   # 按no排序a_list.sort(key=lambda a: a.name) # 按name排序

必须实现”__eq__”和”__hash__”方法。
“__eq__”用于判断是否相等,”__hash__”用于计算hash值。
因为set存取的必须是不可变类型,它是依赖”__hash__”来计算桶的位置,而利用”__eq__”来判断元素之间是否相等。
关于其更多的介绍:https://segmentfault.com/a/1190000003969462

  • 新建一个list,循环遍历
class A:    def __init__(self, no, name):        self.no = no        self.name = name    def __eq__(self, other):        return self.no == other.no and self.name == other.name    def __repr__(self):        return str(self.no)+":"+self.namea_list = [A(1, "a"), A(2, "a"), A(1, "a"), A(1, "b")]new_a_list = []for a in a_list:    if a not in new_a_list:        new_a_list.append(a)

注意这里实现了”__eq__”方法,才能使得“if a not in new_a_list:”语句生效。

  • 使用字典dict记录
    如果不想实现”__eq__”方法,且元素存在”主键”属性(根据其区分对象相等不相等),则可以使用字典dict来记录列表元素出现与否(置0或1),然后遇到非0的就删除该元素即可。
class A:    def __init__(self, no, name):        self.no = no        self.name = name    def __repr__(self):        return str(self.no)+":"+self.name# no为"主键"a_list = [A(1, "a"), A(2, "b"), A(1, "a"), A(3, "b")]mp = {}for a in a_list:    if a.no not in mp:        mp[a.no] = 1    else:        mp[a.no] += 1        a_list.remove(a)