Python中的集合(set)是一种无序且不重复的数据结构,它主要用于以下用途:
去重:
集合可以快速去除列表中的重复元素。
my_list = [1, 2, 3, 4, 2, 3, 1, 2, 2]
my_set = set(my_list)
print(list(my_set)) 结果:[1, 2, 3, 4]
关系测试:
集合支持集合运算,如交集、并集、差集等,用于判断元素之间的关系。
set1 = {1, 2, 3}
set2 = {2, 3, 4}
intersection = set1 & set2 交集
union = set1 | set2 并集
difference = set1 - set2 差集
成员关系测试:
集合可以用来判断一个元素是否存在于集合中,时间复杂度为O(1)。
nums = [1, 2, 3, 4, 5]
exclude_set = {2, 3}
filtered_nums = [num for num in nums if num not in exclude_set]
print(filtered_nums) 结果:[1, 4, 5]
集合操作:
集合支持添加、删除元素,以及清空集合等操作。
my_set = {1, 2, 3}
my_set.add(4) 添加元素
print(my_set) 结果:{1, 2, 3, 4}
my_set.remove(2) 删除元素
print(my_set) 结果:{1, 3}
my_set.clear() 清空集合
print(my_set) 结果:set()
其他用途:
集合还可以用于统计字符出现次数、判断列表是否包含另一个列表的所有元素等。
集合的这些特性使得它在处理需要去重和快速成员关系测试的场景时非常有用,同时简化了代码并提高了运算效率