码迷,mamicode.com
首页 > 编程语言 > 详细

Python 列表元素去重的3种方法

时间:2014-11-29 17:38:19      阅读:256      评论:0      收藏:0      [点我收藏+]

标签:python

以前面试的时候遇到过这个问题,今天闲着整理了以下,大概想到以下三种方法。


<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种方法

标签:python

原文地址:http://blog.csdn.net/hongkangwl/article/details/41596943

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!