python 列表、字典和集合的添加和删除操作
作者:莽原奔马668 时间:2022-06-03 14:25:30
在python中,元组不可变,只能查询不能修改,列表、字典和集合的基本操作,各不相同,下面就来比较一下它们的添加和删除操作吧。
添加
一、列表
1.“+”号
#两个数组相加,生成一个大数组
a = [1, 2, 3]
b = [4, 5, 6]
c = a + b
print(c)
#输出结果:[1, 2, 3, 4, 5, 6]
2.extend方法
#只接受列表参数并将参数的每个元素都添加到原有的列表中
a = [1, 2, 3]
b = [4, 5, 6]
a.extend(b)
print(a)
#输出结果:[1, 2, 3, 4, 5, 6]
3.append方法
#添加任意对象到列表的末端
a = [1, 2, 3]
b = [4, 5, 6]
a.append(b)
print(a)
#输出结果:[1, 2, 3, [4, 5, 6]]
4.insert方法
#添加任意对象到列表中,要指定插入的位置
a = [1, 2, 3]
b = [4, 5, 6]
a.insert(2, b)
print(a)
#输出结果:[1, 2, [4, 5, 6], 3]
二、字典
dict[key] = value
#dict中没有key,是添加操作,有key,是修改操作
三、集合
集合在添加元素之前会进行判断,添加的是已有的元素,集合不变。
1.add方法
s.add("a")
2.update方法
s.update("a")
删除
一、列表
1.del方法
del a[2] #删除a列表中,索引为2的元素
del a #删除a列表对象
2.remove方法
a.remove(2) #删除a列表中,第一次出现的元素2
3.pop方法
a.pop(2) #删除a列表中,索引为2的元素
二、字典
1.pop方法
d.pop(key) #删除key对应的value,key不存在会报错
2.clear方法
d.clear() #清空字典,但是字典对象还在
3.del方法
del d[key] #删除key对应的value
del d #删除字典对象
三、集合
remove方法
s.remove("a")
#删除集合中的元素"a"
来源:https://www.jianshu.com/p/57df77e831cb
标签:python,列表,字典,集合
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
如何确定Oracle数据库表重复的记录
2010-07-26 13:23:00
Django 后台带有字典的列表数据与页面js交互实例
2021-12-01 01:59:39
Case和If哪个更好用?
2009-10-28 18:25:00
跨平台、多浏览器页面测试
2008-06-24 11:54:00
![](https://img.aspxhome.com/file/UploadPic/20086/24/2008624115920735s.gif)
python urllib爬取百度云连接的实例代码
2022-03-07 19:06:28
![](https://img.aspxhome.com/file/2023/0/93850_0s.png)
Pytorch中torch.repeat_interleave()函数使用及说明
2022-06-17 04:18:53
![](https://img.aspxhome.com/file/2023/6/120966_0s.png)
Python实现K折交叉验证法的方法步骤
2021-08-04 13:58:25
Python实现的绘制三维双螺旋线图形功能示例
2023-02-21 20:37:15
![](https://img.aspxhome.com/file/2023/4/96924_0s.png)
Python实现从url中提取域名的几种方法
2022-03-14 12:55:30
windows下Python安装、使用教程和Notepad++的使用教程
2023-04-21 09:31:39
![](https://img.aspxhome.com/file/2023/6/86366_0s.png)
python3在各种服务器环境中安装配置过程
2021-10-27 22:49:55
“你帮我把这个做成这个样子!”—当我听到这句话
2009-04-16 12:57:00
asp 随机字符串函数
2011-04-04 11:01:00
详解Python绘图Turtle库
2021-11-29 05:42:06
![](https://img.aspxhome.com/file/2023/3/65903_0s.png)
ASP四级连动下拉列表程序段
2009-07-03 15:33:00
python基于 Web 实现 m3u8 视频播放的实例
2022-06-15 22:16:40
利用Python3分析sitemap.xml并抓取导出全站链接详解
2022-01-26 16:27:08
![](https://img.aspxhome.com/file/2023/8/68358_0s.png)
python处理两种分隔符的数据集方法
2023-06-17 11:24:54
![](https://img.aspxhome.com/file/2023/9/121389_0s.jpg)
基于Python实现快递信息提取
2022-05-02 13:41:11
![](https://img.aspxhome.com/file/2023/0/126970_0s.jpg)
成功的用户界面的八个特性[译]
2009-04-20 20:36:00
![](https://img.aspxhome.com/file/UploadPic/20094/20/01-77s.jpg)