Python列表的去重方式
class DelListRepeatElement: """ 列表的去重方式 列表可变 去重得到的是一个新列表:原列表不变 """ def __init__(self, aimlist): self.aimlist = aimlist def firstmethod(self): """ 第一种方式:利用集合 集合:元素唯一,不会出现重复的元素 """ newlist = list(set(self.aimlist)) print(f"第一种去重方式-集合:{newlist}") def secondmethod(self): """ 第二种方式:利用for循环 """ newlist = list() for i in self.aimlist: if i not in newlist: newlist.append(i) print(f"第二种去重方式-for循环:{newlist}") def thirdmethod1(self): """ 第三种去重方式:利用字典 字典的键,具有唯一性,所以可以用列表的元素作为键构建一个字典 这样得到的字典的键就是去重后的元素 """ newdict = dict() for i in self.aimlist: newdict.update({i: None}) # 处理字典 newlist = list(newdict.keys()) print(f"第三种去重方式1-字典:{newlist}") # print(newdict) def thirdmethod2(self): """ 利用字典的fromkeys方法 fromkeys,用一个可迭代对象,生成一个字典,可指定字典的值 """ newlist = list({}.fromkeys(self.aimlist).keys()) print(f"第三种去重方式2-字典:{newlist}") if __name__ == "__main__": alist = [1, 2, 3, 4, 5, 6, 6, 5, 4, 3, 2, 1] print(f"需要去重的列表:{alist}") instance = DelListRepeatElement(alist) instance.firstmethod() instance.secondmethod() instance.thirdmethod1() instance.thirdmethod2() # 需要去重的列表: [1, 2, 3, 4, 5, 6, 6, 5, 4, 3, 2, 1] # 第一种去重方式 - 集合:[1, 2, 3, 4, 5, 6] # 第二种去重方式 - for循环: [1, 2, 3, 4, 5, 6] # 第三种去重方式1 - 字典: [1, 2, 3, 4, 5, 6] # 第三种去重方式2 - 字典: [1, 2, 3, 4, 5, 6]