首页 > 代码库 > Python 列表元素去重的3种方法
Python 列表元素去重的3种方法
以前面试的时候遇到过这个问题,今天闲着整理了以下,大概想到以下三种方法。
<span style="font-size:18px;">class delect_duplicate: def method_set(self,mlist): print("method_set is called") print("before process mlist is", mlist) l2 = set(mlist) print("after processed by method_xunhuan, the mlist is",l2) def method_xunhuan(self,mlist): print("method_xunhuan is called") print("before process mlist is", mlist) if mlist: mlist.sort() last = mlist[-1] for i in range(len(mlist) - 2, -1, -1): if last == mlist[i]: del mlist[i] else: last = mlist[i] print("after processed by method_xunhuan, the mlist is",mlist) def method3(self,mlist): print("method3 is called") print("before process mlist is", mlist) temp = [] [temp.append(i) for i in mlist if not i in temp] print("after processed by method3, the result is",temp)</span>
第一种方法直接用set方法,简单粗暴有效,但是因为太简单,往往不能满足面试官的,
第二种方法是对列表的元素排序后从后往前比较,去除相同元素,但是前两种方法都有一个缺点,就是处理后元素的位置改变了,
第三种方法是用两个列表进行处理,不改变元素的位置,测试代码如下:
<span style="font-size:18px;">if __name__ == '__main__': A = [1, 5, 4, 8, 9, 2, 4, 5, 1] B = [1, 5, 4, 8, 9, 2, 4, 5, 1] C = [1, 5, 4, 8, 9, 2, 4, 5, 1] s = delect_duplicate() s.method_set(A) s.method_xunhuan(B) s.method3(C)</span>
运行结果如下:
<span style="font-size:18px;">method_set is called before process mlist is [1, 5, 4, 8, 9, 2, 4, 5, 1] after processed by method_xunhuan, the mlist is {1, 2, 4, 5, 8, 9} method_xunhuan is called before process mlist is [1, 5, 4, 8, 9, 2, 4, 5, 1] after processed by method_xunhuan, the mlist is [1, 2, 4, 5, 8, 9] method3 is called before process mlist is [1, 5, 4, 8, 9, 2, 4, 5, 1] after processed by method3, the result is [1, 5, 4, 8, 9, 2]</span>
完整代码:https://github.com/wlseu/delectdumplicate
Python 列表元素去重的3种方法
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。