python集合怎么去除重复元素
Python集合本身就是一种去重的数据类型,可以直接将列表、元组等数据类型转换成集合,即可去除重复元素。例如:
list1 = [1, 2, 3, 2, 4, 3]
set1 = set(list1)
print(set1) # {1, 2, 3, 4}
同时,集合还支持多种去重操作,例如使用add()方法添加元素时,如果集合中已经存在相同的元素,则不会重复添加:
set2 = set()
set2.add(1)
set2.add(2)
set2.add(1)
print(set2) # {1, 2}
除此之外,集合还支持使用union()方法和intersection()方法进行去重操作,例如:
set3 = set([1, 2, 3])
set4 = set([2, 3, 4])
set5 = set3.union(set4)
print(set5) # {1, 2, 3, 4}
set6 = set3.intersection(set4)
print(set6) # {2, 3}
``
原文地址: https://www.cveoy.top/t/topic/hjlF 著作权归作者所有。请勿转载和采集!