XAMPP案例 622浏览

# Set集合详解

## 集合定义

``````>>> basket = {'apple', 'orange', 'pear', 'orange', 'banana'}
>>> print(basket)   # show that duplicates have been removed
{'banana', 'pear', 'apple', 'orange'}  # 注意，不存在重复的元素
``````

## set函数

set函数用于创建集合

``````>>> empty_set = set()
>>> empty_set
set()
``````

## 集合运算

``````>>> seta = set("ishouke")
>>> setb = set("showmeke")
>>> seta
{'u', 's', 'e', 'o', 'h', 'i', 'k'}
>>> setb
{'w', 's', 'e', 'm', 'o', 'h', 'k'}
``````

``````>>> seta - setb
{'u', 'i'}
``````

``````>>> seta | setb
{'u', 'w', 's', 'e', 'm', 'o', 'h', 'i', 'k'}
``````

``````>>> seta & setb
{'e', 'o', 'h', 'k', 's'}
``````

``````>>> seta ^ setb
{'w', 'u', 'm', 'i'}
``````

## 集合函数

``````>>> myset.add(1)
>>> myset
{1}
>>> myset
{1, 2}
``````

### set.remove(x)移除指定元素

``````>>> myset
{1, 2}
>>> myset.remove(2)
>>> myset
{1}
``````

### set.update(iterable) 更新集合

``````>>> myset = set()
>>> myset.update([2,3,'a'])
>>> myset
{2, 3, 'a'}

>>> myset.update((6,7))
>>> myset
{2, 3, 'a', 6, 7}
>>> myset.update({"a":"a1", "b":"b1"})
>>> myset
{2, 3, 'b', 6, 7, 'a'}
>>> myset.update("mystr")
>>> myset
{2, 3, 6, 7, 'y', 't', 's', 'm', 'b', 'a', 'r'}
``````

``````>>> myset.update(1)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'int' object is not iterable
``````

### set.clear() 清空集合

``````>>> myset
{1, 2}
>>> myset.clear()
>>> myset
set()
``````

## set comprehensions

``````>>> a = {x for x in "abracadabra" if x not in 'abc'}
>>> a
{'d', 'r'}
``````

## 集合分解

``````>>> x, y = {"i", "shou"}
>>> x
'shou'
>>> y
'i'
``````

## 集合比较

``````>>> {3, 2} == {2, 3}
True
>>> {3,2} == {2, 3, 5}
False
``````

#集合转字符串

``````>>> str({1, 'a', 'b44'})
"{1, 'a', 'b44'}"
``````

``````>>> str_set = '{1, 2}'
>>> to_set = eval(str_set)
>>> to_set
{1, 2}``````