Python中set是一种无序无重复元素的数据结构,叫做集合
支持&(求交),|(联合),-(求差),^(求对称差集)的运算
大括号和set()方法可以用来创建集合,想要常见空集合必须使用set()方法而不是{}方法,后面一种方法用来创建空字典
>>>fruit = {'apple', 'banana', 'pear', 'orange'}
>>>print(fruit)
{'apple','banana', 'orange', 'pear'}
>>>'orange' in fruit
True
>>>'yellor' in fruit
False
可以使用{}来创创建集合,使用in来判断元素是否在集合中
>>>a =set(‘abcde’)
>>>a
>>>{a,b, c, d, e}
这里的set相当于强制类型转换,set括号里面的类型必须是序列类型,string类型也支持,
>>> a =set('abcde')
>>> b =set('cdefg')
>>> a
{'b', 'c', 'a','d', 'e'}
>>> a –b # a中有b中没有
{'b', 'a'}
>>> a |b # a中有的或者是b中有的
{'c', 'd', 'e','b', 'g', 'a', 'f'}
>>> a& b # a和b中都有的
{'c', 'd', 'e'}
>>> a ^b # a有b没有或者是b有a没有
{'b', 'g', 'a','f'}
向集合中添加或者是弹出元素
>>> a ={'a', 'b', 'c', 'd'}
>>> a.pop()
'c'
>>>a.add('z')
>>> a
{'z', 'a', 'd','b'}
>>>