在Python中,set() 函数用于创建一个集合(set)。集合是一个无序的不重复元素序列。这里有一些关于如何使用 set() 函数的实际案例:
empty_set = set()print(empty_set) # 输出:set()从列表创建集合:my_list = [1, 2, 3, 4, 4, 5, 6, 6]my_set = set(my_list)print(my_set) # 输出:{1, 2, 3, 4, 5, 6},注意重复的元素被去除了从字符串创建集合:my_string = "hello world"my_set = set(my_string)print(my_set) # 输出:{'h', 'e', 'l', 'o', ' ', 'w', 'r', 'd'},注意重复的字符被去除了集合的基本操作:set1 = {1, 2, 3, 4, 5}set2 = {4, 5, 6, 7, 8}# 并集union_set = set1.union(set2)print(union_set) # 输出:{1, 2, 3, 4, 5, 6, 7, 8}# 交集intersection_set = set1.intersection(set2)print(intersection_set) # 输出:{4, 5}# 差集difference_set = set1.difference(set2)print(difference_set) # 输出:{1, 2, 3}# 对称差集symmetric_difference_set = set1.symmetric_difference(set2)print(symmetric_difference_set) # 输出:{1, 2, 3, 6, 7, 8}判断子集和超集:set1 = {1, 2, 3}set2 = {1, 2, 3, 4, 5}# 判断子集is_subset = set1.issubset(set2)print(is_subset) # 输出:True# 判断超集is_superset = set2.issuperset(set1)print(is_superset) # 输出:True这些实际案例展示了如何在Python中使用 set() 函数以及集合的基本操作。


