Python基础学习(二)

文章目录

集合

  • 集合(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
列表 元组 集合间的转换
相关推荐
麻雀飞吧10 小时前
最新量化学习路径,交易认知和技术实现要并行
人工智能·python
段一凡-华北理工大学12 小时前
向量数据库实战:选型、调优与落地~系列文章12:文本分块策略实战:chunk_size 怎么选?重叠多少?
开发语言·数据库·后端·oracle·rust·工业智能体·高炉智能化
Ljwuhe12 小时前
C++——多态
开发语言·c++
遇乐的果园12 小时前
前端学习笔记-vue加载渲染优化
前端·笔记·学习
心平气和量大福大13 小时前
C#-WPF-Window主窗体
开发语言·c#·wpf
遇乐的果园14 小时前
前端学习笔记-vue状态管理优化
前端·笔记·学习
从零开始的代码生活_14 小时前
C++ 继承详解:访问控制、对象模型、菱形继承与设计取舍
开发语言·c++·后端·学习·算法
云小逸14 小时前
【C++ 第七阶段:模板、泛型编程与工程综合详解】
开发语言·c++
C^h14 小时前
python函数学习
人工智能·python·机器学习
Fanta丶14 小时前
4.Python set()集合、dict(字典、映射)、 数据容器的通用功能
python