python set函數(shù)的使用方法是什么

小億
82
2024-03-08 14:32:21

set()函數(shù)用于創(chuàng)建一個(gè)集合(set),集合是無(wú)序、不重復(fù)的元素的集合。

使用方法如下:

  1. 創(chuàng)建一個(gè)空集合:
my_set = set()
  1. 創(chuàng)建一個(gè)包含元素的集合:
my_set = set([1, 2, 3, 4, 5])
  1. 添加元素到集合中:
my_set.add(6)
  1. 刪除元素從集合中:
my_set.remove(1)
  1. 集合的操作:
set1 = {1, 2, 3}
set2 = {3, 4, 5}
union_set = set1.union(set2)  # 求并集
intersection_set = set1.intersection(set2)  # 求交集
difference_set = set1.difference(set2)  # 求差集

0