在Python中,可以使用大括号{}或者set()函数来创建一个集合(set)。集合是一个无序的、不重复的元素序列。
创建集合的方法如下:
-
使用大括号
{}创建集合,元素之间用逗号,分隔。例如:my_set = {1, 2, 3, 4, 5} -
使用
set()函数创建集合,传入一个可迭代对象(如列表、元组等)作为参数。例如:my_set = set([1, 2, 3, 4, 5]) my_set = set((1, 2, 3, 4, 5))
操作集合的方法有很多,以下是一些常用的方法:
-
添加元素:使用
add()方法向集合中添加一个元素。例如:my_set = {1, 2, 3} my_set.add(4) print(my_set) # 输出:{1, 2, 3, 4} -
删除元素:使用
remove()方法从集合中删除一个元素。如果元素不存在,会抛出KeyError异常。例如:my_set = {1, 2, 3} my_set.remove(2) print(my_set) # 输出:{1, 3}要避免异常,可以使用
discard()方法,如果元素不存在,不会抛出异常。例如:my_set = {1, 2, 3} my_set.discard(2) print(my_set) # 输出:{1, 3} -
集合长度:使用
len()函数获取集合中元素的个数。例如:my_set = {1, 2, 3, 4, 5} print(len(my_set)) # 输出:5 -
判断元素是否存在:使用
in关键字判断一个元素是否在集合中。例如:my_set = {1, 2, 3, 4, 5} print(3 in my_set) # 输出:True print(6 in my_set) # 输出:False -
遍历集合:使用
for循环遍历集合中的元素。例如:my_set = {1, 2, 3, 4, 5} for item in my_set: print(item) -
集合运算:集合之间可以进行并集(
union)、交集(intersection)、差集(difference)等运算。例如:set_a = {1, 2, 3, 4, 5} set_b = {4, 5, 6, 7, 8} # 并集 union_set = set_a.union(set_b) print(union_set) # 输出:{1, 2, 3, 4, 5, 6, 7, 8} # 交集 intersection_set = set_a.intersection(set_b) print(intersection_set) # 输出:{4, 5} # 差集 difference_set = set_a.difference(set_b) print(difference_set) # 输出:{1, 2, 3}

便宜VPS测评









