文章目录
-
- 集合
-
- 集合的方法
- 集合的操作
-
- 获取两个集合的差集---difference函数
- 集合的交集--intersection
- [集合的并集 -- union](#集合的并集 -- union)
- 集合中的isdisjoint
- 数据类型之间的转换
-
- 字符串与数字之间的转换
- 字符串与列表之间的转换
-
- [字符串转列表的函数 -- split](#字符串转列表的函数 -- split)
- [列表转字符串的函数 --- jion](#列表转字符串的函数 --- jion)
- 字符串排序
- 字符串与bytes类型转换
-
- 什么是比特类型-bytes
- [字符串转bytes的函数 -- decode](#字符串转bytes的函数 -- decode)
- [bytes转字符串的函数 -- decode](#bytes转字符串的函数 -- decode)
- [列表 元组 集合间的转换](#列表 元组 集合间的转换)
集合
- 集合(Set)是一个无序的不重复元素序列
- 常用来堆两个列表进行交并差的处理
- 集合与列表一样,支持所有的数据类型,字典除外
示例: {'name', 1, 'zhansang'}

集合的创建
- 通过set函数来创建集合,不能使用{}来创建集合,与字典冲突
Python
a_set = set() #空集合
a_set = set([1, 2, 3]) #传入列表和元组
b_set = {1,2,3} #传入元素
c_set = {} # X,非集合,字典类型
使用集合给列表去重
Python
list_1 = [1, 2, 3, 3, 4]
print(set(list_1)) # {1, 2, 3, 4}
集合的方法
add
用于集合中添加一个元素,重复的元素不会被添加
python
b_set = {1,2,3} #传入元素
b_set.add("a")
print(b_set) # {1, 2, 3, 'a'}
update
加入一个新的集合(或者列表、元组、字符串),如果新的集合内的元素在原集合中存在则无视
python
b_set = {1,2,3} #传入元素
b_set.add("a")
print(b_set) # {1, 2, 3, 'a'}
list_1 = [1, 2, 3, 3, 4, 5, 6]
b_set.update(list_1)
print(b_set) # {1, 2, 3, 4, 5, 6, 'a'}
remove
将集合中的元素删除,如果不存在就报错
python
b_set.remove("a")
print(b_set) # {1, 2, 3, 4, 5, 6}
clear
清空当前集合中的所有元素
python
b_set.clear()
print(b_set) # set()
del
删除集合

说明:
- 集合无法通过索引获取元素
- 集合无获取元素的任何方法,只能通过循环获取
- 集合知识用来处理列表或者元组的一种临时类型,不适合存储与传输
集合的操作
获取两个集合的差集---difference函数

python
d_set = {1,2,3}
f_set = {2,3,5}
d_diff = d_set.difference(f_set)
print(d_diff) # {1}
集合的交集--intersection

python
d_set = {1,2,3}
f_set = {2,3,5}
d_intersection = d_set.intersection(f_set)
print(d_intersection) # {2, 3}
集合的并集 -- union

python
d_set = {1,2,3}
f_set = {2,3,5}
d_union = d_set.union(f_set)
print(d_union) # {1, 2, 3, 5}
集合中的isdisjoint
功能:判断两个集合是否包含相同的元素,如果没有返回Ture,有则返回False
用法:

python
d_set = {1,2,3}
f_set = {2,3,5}
d_isdisjoint = d_set.isdisjoint(f_set)
print(d_isdisjoint) # False
数据类型之间的转换
字符串与数字之间的转换

字符串与列表之间的转换
字符串转列表的函数 -- split
python
list_str = 'a,b,c,d'
list_01 = list_str.split(',')
print(list_01) # ['a', 'b', 'c', 'd']
print(list_str.split(',', 1)) # ['a', 'b,c,d']
列表转字符串的函数 --- jion
注意:列表中的数据类型必须是字符串

python
str_list = ['q','s','w']
print(','.join(str_list)) # q,s,w
字符串排序
python
sort_str = 'abdgrhxck'
res = sorted(sort_str)
print(res) # ['a', 'b', 'c', 'd', 'g', 'h', 'k', 'r', 'x']
print(''.join(res)) # abcdghkrx
字符串与bytes类型转换
什么是比特类型-bytes
- 二进制的数据流 -- bytes
- 一种特殊的字符串
- 字符串前 + b 标记
字符串转bytes的函数 -- decode
python
bytes_str = 'a'
res = bytes_str.encode('utf-8')
print(res) # b'a'
bytes转字符串的函数 -- decode
python
bytes_str = 'a'
res = bytes_str.encode('utf-8')
print(res.decode('utf-8')) # a
列表 元组 集合间的转换
