#创建一个空集合 >>> set1 = set() >>> set1 set() #创建一个具有数据的集合 >>> set2 = {1, 'a', 'apple', 11.22} >>> set2 {11.22, 1, 'apple', 'a'} >>> set3 = set([1, 2, 3]) >>> set3 {1, 2, 3} >>> set('123456') {'3', '6', '4', '5', '2', '1'}
>>> set1={2,1,3} >>> set1.add(4) >>> set1 {1, 2, 3, 4}
>>> set1.update({5,6}) >>> set1 {1, 2, 3, 4, 5, 6} >>> set1.update([7,8]) >>> set1 {1, 2, 3, 4, 5, 6, 7, 8} >>> set1.update((9,10)) >>> set1 {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
>>> set1.remove(1) >>> set1 {2, 3, 4, 5, 6, 7, 8, 9, 10}
>>> set1.discard(1) >>> set1 {2, 3, 4, 5, 6, 7, 8, 9, 10}
>>> set2=set1.pop() >>> set2 2 >>> set1 {3, 4, 5, 6, 7, 8, 9, 10}
len(): 计算集合中元素个数
>>> set1 {4, 5, 6, 7, 8, 9, 10} >>> len(set1) 7
x in s: 判断元素 x 是否在集合 s 中,存在返回 True,不存在返回 False
>>> set1 {4, 5, 6, 7, 8, 9, 10} >>> 1 in set1 False >>> 4 in set1 True
s.clear(): 清空集合
>>> set1.clear() >>> set1 set()