【python基础语法三】列表,元组,集合,字典相关操作
列表的相关操作
1. 列表的拼接 (同元组)
lst1 = ["hello","world"]
lst2 = ["hello","python"]
res = lst1 + lst2
print(res) # ["hello","world","hello","python"]
2. 列表的重复 (同元组)
res = lst1 * 3
print(res) # ["hello","world","hello","world","hello","world"]
3. 列表的切片 (同元组)
"""
语法 => 列表[::] 完整格式:[开始索引:结束索引:间隔值]
(1)[开始索引:] 从开始索引截取到列表的最后
(2)[:结束索引] 从开头截取到结束索引之前(结束索引-1)
(3)[开始索引:结束索引] 从开始索引截取到结束索引之前(结束索引-1)
(4)[开始索引:结束索引:间隔值] 从开始索引截取到结束索引之前按照指定的间隔截取列表元素值
(5)[:]或[::] 截取所有列表
"""
lst = ["a", "b", "c", "d", "e", "f", "g"]
# (1)[开始索引:] 从开始索引截取到列表的最后
res =lst[2:]
print(res) # ["c", "d", "e", "f", "g"]
# (2)[:结束索引] 从开头截取到结束索引之前(结束索引-1)
res =lst[:3]
print(res) # ["a", "b", "c"]
# (3)[开始索引:结束索引] 从开始索引截取到结束索引之前(结束索引-1)
res = lst[3:5]
print(res) # ["d", "e"]
# (4)[开始索引:结束索引:间隔值] 从开始索引截取到结束索引之前按照指定的间隔截取列表元素值
# 正向截取
res = lst[::5]
print(res) # 0 5 10 ["a", "f"]
# 逆向截取
res = lst[::-3] # -1 -4 -7
print(res) # ["g", "d", "a"]
# (5)[:]或[::] 截取所有列表
res = lst[:]
res = lst[::]
print(res) # ["a", "b", "c", "d", "e", "f", "g"]
4. 列表的获取 (同元组)
# 0 1 2
lst = [10,20,30]
# -3 -2 -1
print(lst[-1]) # 30
5. 列表的修改 ( 可切片形式 )
lst = ["孟凡伟","康与众","张宇","赵沈阳","需保障","梁新宇","沈思雨"]
# 改单个值
lst[1] = "陈璐"
print(lst)
# 1.改多个值 (如果使用切片进行修改,要求数据必须是Iterable可迭代性数据)
lst[1:4] = ["孙悟空","猪八戒","白骨精"] # ["孟凡伟","孙悟空","猪八戒","白骨精","需保障","梁新宇","沈思雨"]
# lst[1:4] = 123 # 报错 TypeError: can only assign an iterable
lst[1:4] = "你好" # ["孟凡伟","你","好","需保障","梁新宇","沈思雨"]
print(lst)
# 2.改多个值(带有步长)
"""带有步长的切片修改,切出几个元素就修改几个元素,数量要一致."""
lst = ["孟凡伟","康与众","张宇","赵沈阳","需保障","梁新宇","沈思雨"]
"""0 3 6 """
lst[::3] = "abc" # ["a","康与众","张宇","b","需保障","梁新宇","c"]
# lst[::3] = "ab" # 报错 ValueError
print(lst)
6. 列表的删除 ( 可切片 )
lst = ["孟凡伟","康与众","张宇","赵沈阳","需保障","梁新宇","沈思雨"]
# 1.一次删一个
# del lst[2]
# print(lst) # ["孟凡伟","康与众","赵沈阳","需保障","梁新宇","沈思雨"]
# 2.一次删一堆
# del lst[1:-1]
# print(lst) # ["孟凡伟","沈思雨"]
# 3.注意点
res = lst[1:-1]
del res # 删除的是res这个变量 和 列表无关
print(lst)
# 额外的注意点: 元组不能修改,但里面的列表元素则是可以修改的
tup = (1,2,3,4,[10,11,12])
print(tup[-1])
tup[-1][-1] = 13
print(tup) # (1,2,3,4,[10,11,13])
列表的常用内置方法
增 删 改 查
1. append
向列表的末尾添加新的元素
"""
功能:向列表的末尾添加新的元素
格式:列表.append(值)
返回值:None
注意:新添加的值在列表的末尾,该函数直接操作原有列表
"""
lst = ["a"]
lst.append("b")
print(lst) # ["a", "b"]
2. insert
在指定索引之前插入元素
lst = ['a', 'b']
# 直接改变原有列表
lst.insert(1,"z")
print(lst) # ["a", "z", "b"]
3. extend
迭代追加所有元素
"""迭代追加的数据是可迭代性数据(容器类型数据,range对象,迭代器)"""
lst = ['hello', 'world']
# tup = (1,2,3)
# lst.extend(tup) # 直接修改原容器 ['hello', 'world',1,2,3]
# strvar = "abc"
# lst.extend(strvar)
lst.extend(range(3))
print(lst)
4. pop
通过指定索引删除元素,若没有索引移除最后那个 (推荐)
"""
功能:通过指定索引删除元素,若没有索引移除最后那个
格式:列表.pop(索引)
返回值:删除的元素
(注意:没有指定索引,默认移除最后一个元素 )
"""
lst = ["a", "b", "c"]
# 不指定下标,默认删除最后一个
res = lst.pop()
print(res) # c
print(lst) # ["a", "b"]
# 指定下标,删除具体某个元素
res = lst.pop(1)
print(res) # b
print(lst)# ["a"]
5. remove
通过给予的值来删除,如果多个相同元素,默认删除第一个
"""
功能:通过给予的值来删除,如果多个相同元素,默认删除第一个
格式:列表.remove(值)
返回值:None
(注意:如果有索引的情况推荐使用pop,效率高于remove)
"""
lst = ["曹静怡","王志国","合理","邓鹏","合理"]
res = lst.remove("合理")
print(res) # None
print(lst) # ["曹静怡","王志国","邓鹏","合理"]
6. clear
清空列表
lst = ["曹静怡","王志国","合理","邓鹏","合理"]
lst.clear()
print(lst) # []
6. 其他相关函数
# 列表中没有 find 函数
# 1. index 获取某个值在列表中的索引
lst = ["曹静怡","王志国","合理","邓鹏","合理","邓鹏辉","邓鹏蓝","合理","邓鹏绿"]
res = lst.index("合理") # 2
res = lst.index("合理",3) # 4
res = lst.index("合理",3,6) # 3 4 5中找
# res = lst.index("合理大") # 报错
print(res)
# 2. count 计算某个元素出现的次数
res = lst.count("合理") # 没有范围的概念
print(res) # 3
# 3. sort 对列表排序
lst = [-90,-100,-1,90,78]
# 从小到大进行排序(默认)
lst.sort()
# 从大到小进行排序
lst.sort(reverse=True)
print(lst)
# 对字符串进行排序(按照ascii编码)
lst = ["kobi","james","jordon","yaoming","yi"]
lst.sort()
print(lst) # ["james","jordon", "kobi","yaoming","yi"]
# 是否可以对中文排序(了解 无规律可循)
lst = ["王文","蔡徐坤"]
lst.sort()
print(lst)
# 4. reverse 列表反转操作
lst = [1,2,"a","蔡徐坤","易烊千玺"]
lst.reverse()
print(lst)
列表的深浅拷贝
copy模块中有 浅拷贝 和 深拷贝 两种方法
- 浅拷贝: 浅拷贝只拷贝外层列表 内层列表跟随原列表进行改变
浅拷贝copy.copy(listvar)
或者listvar.copy()
- 深拷贝: 拷贝整个列表 内外列表都不跟随原列表进行改变
深拷贝copy.deepcopy(listvar)
注意: copy模块的copy方法 和 python内置的函数copy一样 都是浅拷贝
# 1.浅拷贝
import copy
"""模块.方法() 同名模块下的同名方法"""
# 方法一 (推荐)
"""
lst1 = [1,2,3]
lst2 = copy.copy(lst1)
lst1.append(10)
print(lst2)
print(lst1)
"""
# 方法二
"""
lst1 = [1,2,3]
lst2 = lst1.copy()
lst1.append(11)
print(lst1)
print(lst2)
"""
# 2.深拷贝
"""把所有层级的容器元素都单独拷贝一份,放到独立的空间中"""
"""
# 现象
lst1 = [1,2,3,[4,5,6]]
lst2 = copy.copy(lst1)
lst1[-1].append(77) # lst2 中最后一个元素也含有77
lst1.append(8888)
print(lst2)
print(lst1)
"""
import copy
lst1 = [1,2,3,[4,5,6]]
lst2 = copy.deepcopy(lst1)
lst1[-1].append(999)
print(lst2)
print(lst1)
# 其他容器的深拷贝
lst1 = (1,2,3,{"a":1,"b":[10,20]})
lst2 = copy.deepcopy(lst1)
lst1[-1]["b"].append(30)
print(lst1)
print(lst2)
"""
总结:
浅拷贝:
只拷贝一级容器中的所有元素独立出一个单独的空间.
深拷贝:
把所有层级的容器中所有元素都单独拷贝一份,形成独立的空间
"""
元组的内置方法
tuple 只有count
index
两个方法,使用方法同上述列表的相同方法。
字典的相关方法
1. 增
(1) 常用-普通方法
dic["top"] = "369"
dic["middle"] = "左手"
dic["bottom"] = "杰克爱"
print(dic)
(2) fromkeys
使用一组键和默认值创建字典
tup = ("a","b","c")
# fromkeys(盛放键的容器,默认值)
dic = {}.fromkeys(tup,None)
print(dic) # {'a': None, 'b': None, 'c': None}
(3) 注意点 (字典中的三个键默认指向的是同一个列表)
dic= {}.fromkeys(tup,[])
print(dic)
dic["a"].append(1)
print(dic) # {'a': [1], 'b': [1], 'c': [1]}
# 改造
dic = {}
dic["top"] = []
dic["middle"] = []
dic["bottom"] = []
dic["top"].append("the boy")
print(dic)
2. 删
(1) pop()
通过键去删除键值对 (若没有该键可设置默认值,预防报错)
dic = {'top': '369', 'middle': '左手', 'bottom': '杰克爱'}
res = dic.pop("middle")
print(res) # 左手
print(dic) # {'top': '369', 'bottom': '杰克爱'}
# 可以给pop设置第二个参数值,以防止键不存在时报错
# 如果没加第二个参数,当key不存在时会报错
res = dic.pop("middle1234","该键不存在")
print(res) # 该键不存在
(2) popitem()
删除最后一个键值对
dic = {'top': '369', 'middle': '左手', 'bottom': '杰克爱'}
res = dic.popitem()
print(res) # {'bottom': '杰克爱'}
print(dic) # {'top': '369', 'middle': '左手'}
(3) clear()
清空字典
dic.clear()
print(dic) # {}
3. 改
update()
批量更新(有该键就更新,没该键就添加)
# 推荐使用
# 没该键就添加
dic_new = {"jungle":"karsa","support":"宝蓝"}
dic = {'top': '369', 'middle': '左手', 'bottom': '杰克爱'}
dic.update(dic_new)
print(dic)
# 有该键就更新
dic_new = {"top":"the bug","support":"xboyww","xiaozhang":"王思聪"}
dic.update(dic_new)
print(dic)
# (了解)
dic.update(ww="王文",zl="张磊")
print(dic)
4. 查
get()
通过键获取值(若没有该键可设置默认值,预防报错)
dic = {"top":"the bug","support":"xboyww","xiaozhang":"王思聪"}
# res = dic["top123"] # 当键不存在时会报错
# get 在获取字典键时,如果不存在,不会发生任何报错,返回的是None
res = dic.get("top123")
# 可以在获取不到该键时,给与默认值提示.
res = dic.get("top123","抱歉,该键不存在")
print(res)
5. 遍历相关
keys()
将字典的键组成新的可迭代对象
dic = {"top":"the bug","support":"xboyww","xiaozhang":"王思聪"}
res = dic.keys()
print(res , type(res)) # <class 'dict_keys'>
for i in res:
print(i)
values()
将字典中的值组成新的可迭代对象 ***
res = dic.values()
print(res , type(res)) # <class 'dict_values'>
items()
将字典的键值对凑成一个个元组,组成新的可迭代对象 ***
res = dic.items()
print(res , type(res))
for k,v in res:
print(k,v)
集合相关操作
交差并补
(1) intersection()
交集
set1 = {"易烊千玺","王一博","刘某PDD","王文"}
set2 = {"倪萍","赵忠祥","金龟子大风车","小龙人","王文"}
res = set1.intersection(set2)
print(res) # {"王文"}
# 简写 &
res = set1 & set2
print(res) # {"王文"}
(2) difference()
差集
res = set1.difference(set2)
print(res)
# 简写 -
res = set1 - set2
print(res) # {"易烊千玺","王一博","刘某PDD"}
(3) union()
并集
res = set1.union(set2)
print(res)
# 简写 |
res = set1 | set2
print(res) # {"易烊千玺","王一博","刘某PDD","倪萍","赵忠祥","金龟子大风车","小龙人","王文"}
(4) symmetric_difference()
对称差集 (补集情况涵盖在其中)
res = set1.symmetric_difference(set2)
print(res)
# 简写 ^
res = set1 ^ set2
print(res) # # {"易烊千玺","王一博","刘某PDD","倪萍","赵忠祥","金龟子大风车","小龙人"}
(5) issubset()
判断是否是子集
set1 = {"刘德华","郭富城","张学友","王文"}
set2 = {"王文"}
res = set2.issubset(set1)
print(res)
# 简写
res = set2 < set1
print(res) # True
(6) issuperset()
判断是否是父集
set1 = {"刘德华","郭富城","张学友","王文"}
set2 = {"王文"}
res = set1.issuperset(set2)
print(res)
# 简写
res = set1 > set2
print(res) # True
(7) isdisjoint()
检测两集合是否不相交 不相交 True 相交False
set1 = {"刘德华","郭富城","张学友","王文"}
set2 = {"王文"}
res = set1.isdisjoint(set2)
print(res) # False 即相交
集合的相关方法
增,删
1. 增
add()
向集合中添加数据
# 一次加一个
set1 = {"王文"}
set1.add("王伟")
print(set1)
update()
迭代着增加
# 一次加一堆
set1 = {"王文"}
lst = ["a","b","c"]
lst = "ppp" # 迭代这添加,无序,会自动去重
set1.update(lst)
print(set1)
2. 删
clear()
清空集合
setvar = {'刘某PDD', '小龙人','倪萍', '赵忠祥'}
setvar.clear()
print(setvar)
pop()
随机删除集合中的一个数据
res = setvar.pop()
print(res) # 小龙人
print(setvar) # 直接改变原集合 #{'刘某PDD', '倪萍', '赵忠祥'}
discard()
删除集合中指定的值(不存在的不删除 推荐使用) ***
setvar.discard("刘某PDD111111") # 元素不存在,也不报错,存在则直接删除,修改原集合
# setvar.discard("刘某PDD") # success 返回值为None
print(setvar)
remove()
删除集合中指定的值(不存在则报错) (了解)
setvar.remove("刘某PDD111") # 元素不存在会报错
setvar.remove("刘某PDD")
print(setvar)
3. frozenset
冰冻集合 (额外了解)
"""frozenset 单纯的只能做交差并补操作,不能做添加或者删除的操作"""
lst = ["王文","宋健","何旭彤"]
fz1 = frozenset(lst)
print(fz1, type(fz1)) # frozenset(["王文","宋健","何旭彤"]) <class 'frozenset'>
# 不能再冰冻集合中添加或者删除元素
# fz1.add(1) # 报错
# fz1.update("abc") # 报错
# fz1.discard("王文") # 报错
# 冰冻集合只能做交差并补
lst2 = ["王文","王同培","刘一缝"]
fz2 = frozenset(lst2)
print(fz2, type(fz2))
# 交集
res = fz1 & fz2
print(res) # frozenset(["王文"])
# 遍历冰冻集合
for i in fz2:
print(i)