0
0
0
1. 云栖社区>
2. 博客>
3. 正文

## set

### 什么是集合？

1.不同元素组成
2.集合是无序的
3.集合中的元素必须是不可变类型。

### 定义集合

s = {1,2,3,4,33,3,4,5}
print(type(s))
---
class 'set'

print(s)
---
{33, 2, 3, 4, 5, 1}

#### 集合是无序的,去重的。

s = {'hello','world','alex','alex'}
print(s)
---
{'alex', 'hello', 'world'}

#### 集合必须是可hash类型

s = {[1,2,3],1}
---
TypeError: unhashable type: 'list'

#### 直接用set定义一个集合

s = set('hello')
print(s)
---
{'l', 'e', 'o', 'h'}

#### 将其它类型转换为set类型

s = set(['alex','alex','hehe'])
print(s)
---
{'hehe', 'alex'}

## 集合的内置放法

s = {1,2,3,4}
print(s)
---
{'s', 1, 2, 3, 4, '3'}

#### clear ---- 清空元素

s.clear()
print(s)
---
set()

#### copy ----复制

s1 = s.copy()
print(s1)
---
{1, 2, 3, 4, 's', '3'}

#### pop ---- 删除,随机的删除,取出

s = {'s',3,1,2,3,4}
s.pop()
print(s)
---
{2, 3, 4, 's'}

#### remove ---- 删除指定元素

s = {'s',3,1,2,3,4}
s.remove(3)
print(s)
---
{1, 2, 4, 's'}

s = {'s',3,1,2,3,4}
print(s)
---
{1, 2, 3, 4, 's'}

## 集合关系运算

python_l = ['ctg','zzgx','zy']
linux_l = ['zy','ctg']
python_and_linux_l = []
for p_name in python_l:
if p_name in linux_l:
python_and_linux_l.append(p_name)
print(python_and_linux_l)
---
['ctg', 'zy']

#### intersection ---- 求两个集合的交集

p_s = set(python_l)
l_s = set(python_l)
print(p_s,l_s)
print(p_s.intersection(l_s))
print(p_s&l_s)
---
{'zy', 'ctg', 'zzgx'} {'hehe', 'zy', 'ctg'}
{'zy', 'ctg'}
{'zy', 'ctg'}

#### union ---- 求并集

python_l = ['ctg','zzgx','zy']
linux_l = ['zy','ctg']
p_s = set(python_l)
l_s = set(linux_l)
print(p_s.union(l_s))
print(p_s|l_s)
---
{'ctg', 'zy', 'zzgx'}
{'ctg', 'zy', 'zzgx'}

#### 差集

 python_l = ['ctg','zzgx','zy']
linux_l = ['zy','ctg','hehe']
p_s = set(python_l)
l_s = set(linux_l)
print(p_s-l_s)
print(l_s-p_s)
print(p_s.difference(l_s))
---
{'zzgx'}
{'hehe'}
{'zzgx'}

#### symmetric_difference ---- 交叉补集 -- 将两个集合中不同的元素取出

python_l = ['ctg','zzgx','zy']
linux_l = ['zy','ctg','hehe']
p_s = set(python_l)
l_s = set(linux_l)
print(p_s.symmetric_difference(l_s))
print(p_s^l_s)
---
{'hehe', 'zzgx'}
{'hehe', 'zzgx'}

## 集合的其它内置方法

#### difference_update ---- 求完差集后直接赋值给p_s.

python_l = ['ctg','zzgx','zy']
linux_l = ['zy','ctg','hehe']
p_s = set(python_l)
l_s = set(linux_l)
print(p_s,l_s)
p_s.difference_update(l_s)      # 等价于 p_s=p_s-l_s
print(p_s)
---
{'zy', 'ctg', 'zzgx'} {'ctg', 'hehe', 'zy'}
{'zzgx'}

#### isdisjoint ---- 如果两个集合之间没交集，则返回一个True

s1={1,2}
s2={3,5}
print(s1.isdisjoint(s2))
---
True

#### issubset ---- 判断一个集合是否是另一个集合的子集

s1 = {1,2}
s2 = {1,2,3}
print(s1.issubset(s2))
print(s2.issubset(s1))
---
True
False

#### issuperset ---- 判断一个集合是否是另一个集合的父集

s1 = {1,2}
s2 = {1,2,3}
print(s1.issubset(s2))
print(s2.issubset(s1))
---
False
True

#### update ---- 将一个集合和另一个集合合并并赋值，可以放多个值

s1={1,2}
s2={1,2,3}
s3={4,5}
s1.update(s2,s3)
print(s1)
---
{1, 2, 3, 4, 5}

#### frozenset ---- 定义不可变集合

s = frozenset('hello')
print(s)
s.pop()
---
Error...报错

#### 将列表去重

names=['alex','alex','wupeiqi']
names=list(set(names))
print(names)
---
{'wupeiqi', 'alex'}
['wupeiqi', 'alex']`

+ 关注