官术网_书友最值得收藏!

Sets

A set is an unordered collection of elements with no duplicates. The basic use of a set is to check membership testing and eliminate duplicate entries. These set objects support mathematical operations, such as union, intersection, difference, and symmetric difference. We can create a set using curly braces or the set() function. If you want create an empty set, then use set(), not {}.

Here is a brief demonstration:

>>> fruits = {'Mango', 'Apple', 'Mango', 'Watermelon', 'Apple', 'Orange'}
>>> print (fruits)
{'Orange', 'Mango', 'Apple', 'Watermelon'}
>>> 'Orange' in fruits
True
>>> 'Onion' in fruits
False
>>>
>>> a = set('abracadabra')
>>> b = set('alacazam')
>>> a
{'d', 'c', 'r', 'b', 'a'}
>>> a - b
{'r', 'd', 'b'}
>>> a | b
{'d', 'c', 'r', 'b', 'm', 'a', 'z', 'l'}
>>> a & b
{'a', 'c'}
>>> a ^ b
{'r', 'd', 'b', 'm', 'z', 'l'}

Set comprehensions are also supported in Python. Refer to the following code:

>>> a = {x for x in 'abracadabra' if x not in 'abc'}
>>> a
{'r', 'd'}
主站蜘蛛池模板: 竹北市| 应城市| 海丰县| 塔城市| 钟祥市| 灵璧县| 东丽区| 南宁市| 汝南县| 科技| 思南县| 平顶山市| 高碑店市| 仁怀市| 马鞍山市| 黄大仙区| 游戏| 衡东县| 柳州市| 禄丰县| 新晃| 福建省| 泰兴市| 修武县| 广平县| 奉贤区| 盐边县| 唐山市| 当涂县| 贵港市| 津市市| 灵宝市| 龙口市| 永福县| 临汾市| 如东县| 监利县| 封丘县| 桂阳县| 信阳市| 宝丰县|