blog/docs/code/python/set.md

80 lines
2.0 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

---
title: Set 集合
date: 2020-07-25 23:00:40
tags: [Python]
categories: [Python]
author: Anges黎梦
---
## 集合 Set
> 集合是一个无序的不重复序列。
> set() 函数创建一个无序不重复元素集,可进行关系测试,删除重复数据,还可以计算交集、差集、并集等。
## 创建集合
```
list_1 = ['a','b','c','d','a','a','b']
print(set(list_1)) # 集合的定义
print(type(set(list_1)))
```
- 定义,用{}直接定义集合或者用set函数创建集合。
- 空集合一定要用set函数来创建因为{}代表创建的是空字典
- 集合分为可变和不可变集合两种set为可变集合frozenset不可变集合
## 基本操作
```
set_1 = set(list_1)
set_1.add('o') # 集合中添加数据,可多个
print(set_1)
set_1.update() # 可以添加列表、元组、字典等,可多个。
set_1.update([1,5,7])
set_1.update({"y":9}) # 如果添加的是字典那么添加进去的只有key
set_1.update(('t','n'))
print(set_1)
```
## del set_1 删除集合
```
set_1.remove(1) # 删除的内容一定要在集合中,否则会抛出异常
print(set_1)
set_1.discard('p') # 删除的内容不在集合中,不会抛出异常
print(set_1)
a = set_1.pop() # 随机删除集合中的某一个元素
print(set_1)
print(a)
```
## len
```
print(len(set_1))
```
## clear
```
set_1.clear()
```
```
print('a' in set_1)
```
## 集合的运算
```
set_2 = {'b', 'd', 'c', 'a'}
set_3 = {'a', 5, 7, 'b', 'n',}
print(set_2 - set_3) # 集合set_2中有而set_3中年没有的元素
print(set_2 | set_3) # 两个集合中包含的所有元素
print(set_2 & set_3) # 两个集合中都包含的元素
print(set_2 ^ set_3) # 不同时包含与两个集合的元素
```
## 内置的方法
```
a= set_2.intersection(set_3) # 返回两个集合的交集
print(a)
print(set_2.isdisjoint(set_3)) # 判断两个集合是否有相同的元素如果没有返回true如果有返回false
print(set_2.union(set_3)) # 返回两个集合的并集
```