多应用+插件架构,代码干净,二开方便,首家独创一键云编译技术,文档视频完善,免费商用码云13.8K 广告
**问:说说Python删除list里的重复元素有几种方法?** **答:**在Python中主要有5种方式,还没看答案,你能想起几种呢,面试笔试题经常碰到的一道题 。 1、使用set函数 set是定义集合的,无序,非重复 ~~~ numList = [1,1,2,3,4,5,4] print(list(set(numList))) #[1, 2, 3, 4, 5] ~~~ 2、先把list重新排序,然后从list的最后开始扫描 ~~~ a = [1, 2, 4, 2, 4, 5,] a.sort() last = a[-1] for i in range(len(a) - 2, -1, -1):     if last == a[i]:         del a[i]     else:         last = a[i] print(a) #[1, 2, 4, 5] ~~~ ##### 3、使用字典函数 ~~~ a=[1,2,4,2,4,] b={} b=b.fromkeys(a) c=list(b.keys()) print(c) #[1, 2, 4] ~~~ ##### 4、append方式 ~~~ def delList(L):     L1 = []     for i in L:         if i not in L1:             L1.append(i)     return L1 print(delList([1, 2, 2, 3, 3, 4, 5])) #[1, 2, 3, 4, 5] ~~~ ##### 5、count + remove方式 ~~~ def delList(L):     for i in L:         if L.count(i) != 1:             for x in range((L.count(i) - 1)):                 L.remove(i)     return L print(delList([1, 2, 2, 3, 3, 4]))#[1, 2, 3, 4] ~~~