欢迎访问我的网站,希望内容对您有用,感兴趣的可以加入免费知识星球。

Python 列表去重的2种方法

Python基础 迷途小书童 4年前 (2020-10-11) 2455次浏览 0个评论

软硬件环境

  • windows 10 64bit
  • anaconda3 with python 3.7

视频看这里

此处是 youtube 的播放链接,需要科学上网。喜欢我的视频,请记得订阅我的频道,打开旁边的小铃铛,点赞并分享,感谢您的支持。

遍历法

这是最容易想到的方法,我们准备一个临时的列表变量 tmp,然后开始遍历原始列表 aList,如果 tmp 中不存在相同的元素,则将元素追加到 tmp 列表中,否则不追加。看下面的代码

(base) PS C:\Windows\system32> 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 information
IPython 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:\Windows\system32> 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 information
IPython 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]: bList
Out[3]: [1, 2, 3, 4]

In [4]:  

有一点,需要注意,使用 set 后生成的列表元素是无法保证其顺序的。如果想继续保持原来的顺序,可以通过列表中索引(index)的方法来实现,看下面的代码

(base) PS C:\Windows\system32> 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 information
IPython 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]: bList
Out[3]: [1, 2, 3, 4]

In [4]: bList.sort(key=aList.index)

In [5]: bList
Out[5]: [4, 3, 2, 1]

In [6]:   

与第一种方法相比,set 的执行效率会提升不少

喜欢 (0)

您必须 登录 才能发表评论!