Python 去重有多种方法:

1.使用 set() 函数

set() 函数是 Python 中的一个内置函数,可以将一个列表或元组转换为集合,并自动去重。例如:

lst = [1, 2, 3, 3, 4, 4, 5]
set_lst = set(lst)
new_lst = list(set_lst)
print(new_lst)

输出:

[1, 2, 3, 4, 5]

2.使用列表推导式

使用列表推导式也可以实现去重。例如:

lst = [1, 2, 3, 3, 4, 4, 5]
new_lst = []
[new_lst.append(i) for i in lst if i not in new_lst]
print(new_lst)

输出:

[1, 2, 3, 4, 5]

3.使用 collections 模块

使用 collections 模块中的 Counter 类可以统计列表中每个元素出现的次数,然后再通过列表推导式去重。例如:

from collections import Counter

lst = [1, 2, 3, 3, 4, 4, 5]
count = Counter(lst)
new_lst = [i for i in count.keys()]
print(new_lst)

输出:

[1, 2, 3, 4, 5]
python 去重

原文地址: https://www.cveoy.top/t/topic/bhfW 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录