本文教程操作环境:windows7系统、Python 3.9.1,DELL G3电脑。
1、列表遍历法
alist = [1, 2, 2, 4, 4, 6, 7] b = list() for i in alist: if i not in b: b.append(i) print(b)
2、集合set去重法
处理起来比较简单,但结果不会保留之前的顺序。
ids = [1,4,3,3,4,2,3,4,5,6,1] ids = list(set(ids))
3、字典中fromkeys()方法
>>> L = [3, 1, 2, 1, 3, 4] >>> T = {}.fromkeys(L).keys() >>> T [1, 2, 3, 4] >>> T.sort(key=L.index) >>> T [3, 1, 2, 4]
4、列表推导式法
>>> lst1 = [2, 1, 3, 4, 1] >>> temp = [] >>> [temp.append(i) for i in lst1 if not i in temp] [None, None, None, None] >>> print(temp) [2, 1, 3, 4]
5、使用sort函数或sorted函数
>>> L = [3, 1, 2, 1, 3, 4] >>> T = sorted(set(L), key=L.index) >>> T [3, 1, 2, 4]
以上就是小编整理总结的列表去重的五种方法,大家可以根据自己的区别选择合适的方法哟~
Copyright © 2019- net188.cn 版权所有 湘ICP备2022005869号-2
违法及侵权请联系:TEL:199 1889 7713 E-MAIL:2724546146@qq.com
本站由北京市万商天勤律师事务所王兴未律师提供法律服务