windows 10 64bit
anaconda3 with python 3.7
遍历法这是最容易想到的方法,我们准备一个临时的列表变量tmp,然后开始遍历原始列表aList,如果tmp中不存在相同的元素,则将元素追加到tmp列表中,否则不追加。看下面的代码
(base) PS C:Windowssystem32> ipythonPython 3.7.6 (default, Jan 8 2020, 20:23:39) [MSC v.1916 64 bit (AMD64)]Type 'copyright', 'credits' or 'license' for more informationIPython 7.13.0 -- An enhanced Interactive Python. Type '?' for help.In [1]: aList = [1, 2, 3, 4, 3, 2, 1]In [2]: tmp = []In [3]: for item in aList: ...: if not item in tmp: ...: tmp.append(item) ...: print(tmp)[1, 2, 3, 4]In [4]:这种方法直观易懂,可以保持原来列表的顺序,但是执行效率偏低
使用set去重set是一个无序且无重复元素的集合,概念上相当于数学上的无序集,数据结构上相当于字典dict的键值。所以,将set作用于列表后,就能达到列表去重的目的。看下面的代码
(base) PS C:Windowssystem32> ipython Python 3.7.6 (default, Jan 8 2020, 20:23:39) [MSC v.1916 64 bit (AMD64)]Type 'copyright', 'credits' or 'license' for more informationIPython 7.13.0 -- An enhanced Interactive Python. Type '?' for help.In [1]: aList = [4, 3, 2, 1, 2, 3, 4]In [2]: bList = list(set(aList))In [3]: bListOut[3]: [1, 2, 3, 4]In [4]:有一点,需要注意,使用set后生成的列表元素是无法保证其顺序的。如果想继续保持原来的顺序,可以通过列表中索引(index)的方法来实现,看下面的代码
(base) PS C:Windowssystem32> ipython Python 3.7.6 (default, Jan 8 2020, 20:23:39) [MSC v.1916 64 bit (AMD64)]Type 'copyright', 'credits' or 'license' for more informationIPython 7.13.0 -- An enhanced Interactive Python. Type '?' for help.In [1]: aList = [4, 3, 2, 1, 2, 3, 4]In [2]: bList = list(set(aList))In [3]: bListOut[3]: [1, 2, 3, 4]In [4]: bList.sort(key=aList.index)In [5]: bListOut[5]: [4, 3, 2, 1]In [6]:与第一种方法相比,set的执行效率会提升不少