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
列表 元组 集合间的转换
相关推荐
xiaoxiaoxiaolll2 小时前
机器学习材料性能预测与材料基因工程
深度学习·学习
ldmd2842 小时前
Go语言实战:应用篇-1:项目基础架构介绍
开发语言·后端·golang
Rousson2 小时前
硬件学习笔记--92 关于UWB的介绍
笔记·学习
froginwe112 小时前
PHP 表单 - 必需字段
开发语言
周杰伦_Jay2 小时前
【Golang 核心特点与语法】简洁高效+并发原生
开发语言·后端·golang
Generalzy2 小时前
轻量级向量库chromadb
python
by__csdn2 小时前
javascript 性能优化实战:垃圾回收优化
java·开发语言·javascript·jvm·vue.js·性能优化·typescript
by__csdn2 小时前
JavaScript性能优化:减少重绘和回流(Reflow和Repaint)
开发语言·前端·javascript·vue.js·性能优化·typescript·vue
玩具猴_wjh2 小时前
12.12 学习笔记
笔记·学习