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

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'}
主站蜘蛛池模板: 如东县| 南江县| 浮山县| 黔江区| 万年县| 辉南县| 库伦旗| 海兴县| 维西| 翼城县| 青铜峡市| 财经| 陇南市| 喜德县| 晋中市| 天门市| 永城市| 定远县| 临沭县| 丰顺县| 溧阳市| 新源县| 南靖县| 旬阳县| 阜宁县| 佛山市| 乌苏市| 哈尔滨市| 焦作市| 安乡县| 浑源县| 柳州市| 沂南县| 治县。| 祁阳县| 合川市| 郴州市| 分宜县| 崇明县| 金塔县| 佛坪县|