1,创建集合
a,直接创建
parame = {‘a‘, ‘b‘, ‘c‘, ‘d‘, ‘e‘} print (parame) >>>{‘d‘, ‘a‘, ‘b‘, ‘c‘, ‘e‘}
b,函数创建
parame = set(‘abcde‘) print (parame) >>>{‘d‘, ‘a‘, ‘b‘, ‘c‘, ‘e‘}
注:创建空集合时用set()函数,而不是{},因为{}直接创建空字典
2,基本操作
a,判断
parame = {‘a‘, ‘b‘, ‘c‘, ‘d‘, ‘e‘} print (‘a‘ in parame) >>>True
3,常用功能
a,追加
add()
parame = {‘a‘, ‘b‘, ‘c‘, ‘d‘, ‘e‘} parame.add(‘vitcor‘) # 添加元素是数字、字符串 print (parame) >>> {‘b‘, ‘c‘, ‘d‘, ‘e‘, ‘vitcor‘, ‘a‘}
update()
parame = {‘a‘, ‘b‘, ‘c‘, ‘d‘, ‘e‘} parame.upadte(‘vitcor‘) # 将添加的字符串分割掉 print (parame) >>>{‘v‘, ‘b‘, ‘c‘, ‘d‘, ‘i‘, ‘r‘, ‘e‘, ‘a‘, ‘o‘, ‘t‘}
parame = {‘a‘, ‘b‘, ‘c‘, ‘d‘, ‘e‘} parame.update([1,2],[‘victor‘,‘maomao‘]) # 添加元素可以是列表,字典,元组 print (parame) >>>{1, 2, ‘b‘, ‘c‘, ‘d‘, ‘victor‘, ‘e‘, ‘maomao‘, ‘a‘}
parame = {‘a‘, ‘b‘, ‘c‘, ‘d‘, ‘e‘} parame.update(‘a‘) print (parame) >>>{‘d‘, ‘a‘, ‘b‘, ‘c‘, ‘e‘} # 元素存在,不进行任何操作
b,删除
remove()
parame = {‘a‘, ‘b‘, ‘c‘, ‘d‘, ‘e‘} parame.remove(‘a‘) # 若元素不存在,将会报错 print (parame) >>>{‘d‘, ‘b‘, ‘c‘, ‘e‘}
discard()
parame = {‘a‘, ‘b‘, ‘c‘, ‘d‘, ‘e‘} parame.discard(‘a‘) # 删除特定元素不存在时,不会报错 print (parame) >>>{‘d‘, ‘a‘, ‘b‘, ‘c‘, ‘e‘}
c,计数
parame = {‘a‘, ‘b‘, ‘c‘, ‘d‘, ‘e‘} x = len(parame) print (x) >>>5
d,清空
parame = {‘a‘, ‘b‘, ‘c‘, ‘d‘, ‘e‘} parame.clear() print (parame) >>>set()
原文:https://www.cnblogs.com/qianqicheng/p/10577281.html