集合(set)是一个无序的不重复元素序列。
可以使用大括号 { } 或者 set() 函数创建集合。
student = {'小明', 'xiaohong', 'adm'}
print('student的数据类型', type(student)) # student的数据类型 <class 'set'>
集合的基本操作
1、添加元素
add()
功能:
用于集合中添加一个元素,如果集合中已存在该元素则函数不执行
用法:
set.add(item)
参数:
item:要添加到集合中的元素
a_list = ['python', 'django', 'django', 'flask']
a_set = set()
a_set.add(a_list[0])
a_set.add(a_list[1])
a_set.add(a_list[2])
a_set.add(a_list[-1])
print(a_set) # {'flask', 'django', 'python'}
# 重复的元素未添加进集合
a_set.add(True)
a_set.add(None)
print(a_set) # {True, None, 'django', 'python', 'flask'}
# 集合是无序的
从上面的例子可以证明:
- 集合是不重复元素的序列
- 集合是无序的
update()
功能:
加入一个新的集合(列表,元素,字符串),如辛几何内的元素在原集合中存在则无视
用法:
set.update(iterable)
参数:
iterable:集合、列表、元组、字符串
# update
a_tuple = ('a', 'b', 'c')
a_set.update(a_tuple)
print(a_set) # {True, None, 'a', 'django', 'c', 'flask', 'b', 'python'}
a_set.update('python')
print(a_set) # {True, 'o', 't', None, 'h', 'a', 'django', 'c', 'flask', 'y', 'n', 'b', 'python', 'p'}
2、移除元素
remove()
功能:
将集合中的某个元素删除,如元素不存在将会报错
方法:
set.remove(item)
参数:
iten:当前集合中的一个元素
clear()
功能:
清空当前集合中的所有元素
用法:
set.clear()
重要说明:
- 集合无法通过索引获取元素
- 集合无法获取元素的任何方法
- 集合只是用来处理列表或元组的一种临时类型,他不适合存储和传输
a_set.remove('python')
print(a_set) # {'p', True, None, 'y', 'a', 't', 'o', 'flask', 'n', 'b', 'h', 'django', 'c'}
a_set.clear()
print(a_set) # set()
a_set.remove('django') # KeyError: 'django'
3、集合的交集
什么是交集?
- a,b两个集合分表拥有的相同的元素集,称为a与b的交集
intersection()
功能:
返回两个或更多集合中都包含的元素,即交集
用法:
a_set.intersection(b_set...)
参数:
b_set...: 与当前集合对比的一个或多个集合
返回值:
返回原始集合与对比集合的交集
a = ['dewei', 'xiaomu', 'xiaohua', 'xiaoguo']
b = ['xiaohua', 'dewei', 'xiaoman', 'xiaolin']
c = ['xiaoguang', 'xiobai', 'dewei', 'xiaooyuan']
a_set = set(a)
b_set = set(b)
c_set = set(c)
print(a_set, b_set, c_set)
result = a_set.intersection(b_set, c_set)
xiaotou = list(result)
print('{}是这个小偷'.format(xiaotou[0]))
3、集合的并集
什么是并集?
- a,b两个集合分表拥有的元素(去掉重复)即为a与b的并集
union()
功能:
- 返回多个集合的并集,即包含了所有集合的元素,重复的元素指挥出现一次
用法:
a_set.union(b_set...)
参数:
b_set...:与当前集合对比一个或多个集合
返回值:
返回原始集合与对比集合的并集
a_school = ['周五半天', '免费周末培训', '周五休息']
b_school = ['放学时间从6点改为5点', '作业少留点', '换舒服的座椅']
c_school = ['作业少留点', '周五半天', '伙食改善']
a_set = set(a_school)
b_set = set(b_school)
c_set = set(c_school)
print(a_set)
print(b_set)
print(c_set)
# help_data = a_set.union(b_set, c_set)
help_data = a_set.union(b_school, c_school)
print(help_data)
4、两个集合的相同元素
isdisjoint()
功能:
判断两个集合是否包含相同的元素,如果没有返回Ture,否则返回False
用法:
a_set.isdisjoint(b_set)
参数:
b_set:当前集合用来判断相同元素的集合
返回值:
返回一个布尔值True或False
company_not_allow = {'女', '喝酒', '睡懒觉'}
one_player = {'男', '跑步', '朝气', '喝酒'}
two_player = {'女', '生活规律', '跆拳道'}
three_player = {'男', '空手道', '年经'}
four_player = {'男', '太极拳'}
print(company_not_allow.isdisjoint(one_player)) # False
print(company_not_allow.isdisjoint(two_player)) # False
print(company_not_allow.isdisjoint(three_player)) # True
print(company_not_allow.isdisjoint(four_player)) # True
数据类型的转换
什么是数据类型转换,为何要做类型转换
- 将自身数据类型变成新的数据类型,并拥有新的数据类型的所有功能的过程即为类型转换
- 为了方便更好的帮助 处理业务,将类型变更为更适合业务场景的类型
字符串与数字之间转换的要求
- str —> number:数字组成的字符串
- number —> str:无要求
原始类型 | 目标类型 | 函数 | 举例 |
---|---|---|---|
整型 | 字符串 | str | new_str = str(123456) |
浮点型 | 字符串 | str | new_str = str(3.14) |
字符串 | 整型 | int | new_int = int(‘12’) |
字符串 | 浮点型 | float | new_float = float(‘1.2’) |
字符串与数字之间的转换函数
# 数字转字符串
int_data = 12
float_data = 3.14
str_int_data = str(int_data)
str_float_data = str(float_data)
print(str_int_data, str_float_data, type(str_int_data), type(str_float_data))
# 12 3.14 <class 'str'> <class 'str'>
# 0和-1转字符串
zero_number = 0
_number = -1
str_zero_number = str(zero_number)
str_number = str(_number)
print(str_zero_number, str_number, type(str_zero_number), type(str_number))
# 0 -1 <class 'str'> <class 'str'>
# 字符串转数字
str_float = '3.14'
str_int = '123456'
real_float = float(str_float)
real_int = int(str_int)
print(real_float, real_int, type(real_float), type(real_int))
# 3.14 123456 <class 'float'> <class 'int'>
# 字符串中包含非数字转换float类型
mix_str = '123a'
# print(float(mix_str)) # ValueError: could not convert string to float: '123a'
# float类型转换int
float_data_str = '3.14'
# test_data = int(float_data_str) # ValueError: invalid literal for int() with base 10: '3.14'
# int 转换 float
int_data_str = '123'
test_data = float(int_data_str)
print(test_data, type(test_data)) # 123.0 <class 'float'>
字符串和bytes类型转换
什么是bytes
- 二进制的数据流–bytes
- 一种特殊的字符串
- 字符串前 + b 标记
查询bytes类型的所有函数
dir()
print(dir(b))
# ['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'capitalize', 'center', 'count', 'decode', 'endswith', 'expandtabs', 'find', 'fromhex', 'hex', 'index', 'isalnum', 'isalpha', 'isascii', 'isdigit', 'islower', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']
字符串转bytes的函数–encode
c = b'hell 小明'
SyntaxError: bytes can only contain ASCII literal characters.
bytes只支持ASCII 类型字符,中文是不支持的,所以需要encode
将字符串转换成bytes
功能:
将字符串转换成bytes类型
用法:
string.encode(encoding='utf-8', errors='strict')
参数:
encoding:转换成的编码格式,如ascii,gbk,默认utf-8
errors:出错是的处理方法,默认strict
直接抛出错误,也可以选择ignore 忽略错误
返回值:
返回一个bytes类型
bytes转字符串的函数–decode
功能:
将bytes类型转换成字符串
方法:
bytes.dncode(encoding='utf-8', errors='strict')
参数:
encoding:转换成的编码格式,如ascii,gbk,默认utf-8
errors:出错是的处理方法,默认strict
直接抛出错误,也可以选择ignore 忽略错误
返回值:
返回一个字符串类型
a = 'hello xiaoming'
print(a, type(a))
b = b'hello xiaoming'
print(b, type(b))
print(b.capitalize()) # b'Hello xiaoming'
print(b.replace(b'xiaoming', b'xiaoqiang')) # b'hello xiaoqiang'
print(b[:3]) # b'hel'
print(b.find(b'x')) # 6
print(dir(b))
c = 'hell 小明'
d = c.encode('utf-8')
print(d, type(d))
print(d.decode('utf-8'))