定义:’’‘集合(Set)
集合是无序和无索引的集合。在 Python 中,集合用花括号编写。’’’

1,创建集合

set_baby = {‘牛犊’, ‘羊仔’, ‘小熊猫’, ‘小猪熊’}
 print(‘小动物集合:’, set_baby)
 #小动物集合: {‘小猪熊’, ‘羊仔’, ‘小熊猫’, ‘牛犊’}

2,遍历集合

#集合是无序的,所以没法用索引来访问,可以遍历来进行访问
 set_AI = {‘xiaoai’, ‘Siri’, ‘xiaodu’, ‘dingdong’}
 for p in set_AI:
 print§
 #xiaodu Siri xiaoai dingdong#检查set_AI中是否有Siri
 print(‘Siri’ in set_AI)
 #True

3,集合元素添加

set_vegetables = {‘玉米’, ‘菠菜’, ‘西红柿’, ‘茄子’}
#添加一个
 set_vegetables.add(‘黄瓜’)
 print(set_vegetables)
 #{‘玉米’, ‘黄瓜’, ‘菠菜’, ‘西红柿’, ‘茄子’}#添加多个
 set_vegetables.update([‘胡萝卜’, ‘油菜’, ‘大头菜’])
 print(set_vegetables)
 #{‘油菜’, ‘大头菜’, ‘玉米’, ‘胡萝卜’, ‘黄瓜’, ‘菠菜’, ‘西红柿’, ‘茄子’}

4,获取集合项目总数

set_daily = {‘早饭’, ‘午饭’, ‘晚饭’, ‘睡觉觉’}
 print(‘每天必做的事一共有几件:’ ,len(set_daily),’,’, set_daily)
 #每天必做的事一共有几件: 4 , {‘睡觉觉’, ‘早饭’, ‘晚饭’, ‘午饭’}

5,删除集合项目

#如果知道准确的项目名称
 set_music = {‘我不是乌龟’, ‘我不是猪八戒’, ‘我是一只皮球’, ‘我什么都不是’, ‘我还是一只蚂蚁’}
 set_music.remove(‘我不是乌龟’)#或者discard
 set_music.discard(‘我不是猪八戒’)
 print(set_music)
 #{‘我是一只皮球’, ‘我还是一只蚂蚁’, ‘我什么都不是’}#pop()删除最后一个
 set_pop = set_music.pop()
 print(‘随机删除最后一个’, set_pop)
 #随机删除最后一个 我是一只皮球#clear清空
 set_music.clear()
 print(‘集合清空了:’, set_music)
 #集合清空了: set()#del彻底删除
 del set_music
 try:
 print(set_music)
 except Exception:
 print(‘没有set_music’)
 #没有set_music

6,合并集合

set_eat = {‘蛋糕’, ‘面包’, ‘饼干’}
 set_drink = {‘可乐’, ‘橙汁’, ‘柠檬茶’}
 set_food = set_eat.union(set_drink)
 print(set_food)
 #{‘蛋糕’, ‘可乐’, ‘橙汁’, ‘柠檬茶’, ‘面包’, ‘饼干’}

7,集合构造函数

set_set = set((“我在”, ‘尝试’, ‘使用’, ‘set’) )
 print(‘构造函数set:’, set_set)
 #构造函数set: {‘set’, ‘我在’, ‘尝试’, ‘使用’}

8,集合找不同

set_color = {‘white’, ‘red’, ‘green’, ‘blue’}
 set_color_02 = {‘white’, ‘red’, ‘yellow’, ‘blue’}
 set_differ = set_color.difference(set_color_02)
 print(‘不一样的颜色是:’, set_differ)
 #不一样的颜色是: {‘green’}
 #set_color 和 set_color_02的区别所以返回的是set_color里的那个