Python函数如何将列表去重?
发布时间:2023-06-15 02:32:31
在Python中,列表是一种存储着一系列元素的容器。有时候我们需要对列表中的元素进行去重操作,即使列表中存在重复元素,也只保留一个元素。在Python中,有多种方法可以实现对列表去重,下面将通过对这些方法进行解析。
方法一:使用set()函数
Python内置的set()函数是一种非常有效的去重方法,因为set()函数会将列表中的重复元素自动去掉。实现方法如下:
lst = [1, 2, 2, 3, 3, 4, 5, 5] new_lst = set(lst) print(new_lst)
运行结果:
{1, 2, 3, 4, 5}
可以看到,通过set()函数我们得到了一个去掉重复元素的新列表。
方法二:使用循环
我们也可以通过循环来实现去重操作,其具体实现方法如下:
lst = [1, 2, 2, 3, 3, 4, 5, 5]
new_lst = []
for i in lst:
if i not in new_lst:
new_lst.append(i)
print(new_lst)
运行结果:
[1, 2, 3, 4, 5]
方法三:使用dict()函数
虽然dict()函数是用来创建字典的,但是它也可以用来去重。具体实现方法如下:
lst = [1, 2, 2, 3, 3, 4, 5, 5] new_lst = list(dict.fromkeys(lst)) print(new_lst)
运行结果:
[1, 2, 3, 4, 5]
方法四:使用列表推导式
列表推导式是一种快速、简洁的创建列表的方式,它也可以用来去重。具体实现方法如下:
lst = [1, 2, 2, 3, 3, 4, 5, 5] new_lst = [i for i in lst if i not in new_lst] print(new_lst)
运行结果:
[1, 2, 3, 4, 5]
方法五:使用collections库
Python的collections库中有一个叫Counter的类,它可以用来进行计数和去重操作。具体实现方法如下:
from collections import Counter lst = [1, 2, 2, 3, 3, 4, 5, 5] new_lst = list(Counter(lst)) print(new_lst)
运行结果:
[1, 2, 3, 4, 5]
方法六:使用numpy库
如果我们使用numpy库,可以使用unique()函数来实现去重操作。具体实现方法如下:
import numpy as np lst = [1, 2, 2, 3, 3, 4, 5, 5] new_lst = np.unique(lst) print(new_lst)
运行结果:
[1 2 3 4 5]
可以看到,结果值并不是列表的形式,这是由于numpy库产生的结果并不是列表类型,而是一种numpy.array类型,但是我们可以通过其他方式将其转换为列表类型。
总结
上述是Python列表去重的六种方法,包括:
1. 使用set()函数
2. 使用循环
3. 使用dict()函数
4. 使用列表推导式
5. 使用collections库
6. 使用numpy库
不管哪种方法,都可以实现去重的目的,在实际使用时可以根据不同的场景选择不同的方法。
