网站首页 > 基础教程 正文
python集合添加元素的两种方法
要为python集合set添加元素之前,应当了解,python的集合有去重的功能,也就是说,当给集合添加了一个已经存在的元素,那么集合中的元素个数和各个元素的值不会有什么变化。那么该如何为python的集合set添加元素呢?这里介绍两种方法:
- 使用python集合内置的方法add()来添加元素;
- 使用集合内置的update()方法来为集合添加元素,参数为集合或其它的可迭代对象。
python集合set添加元素实例代码
#add()方法
>>> set1 = set()
>>> set1.add(1)
>>> set1
{1}
#update()方法
>>> set1.update({2})
>>> set1
{1, 2}
>>> set1.update([3,5,6])
>>> set1
{1, 2, 3, 5, 6}
猜你喜欢
- 2024-10-31 如何用 GitHub Actions 写出高质量的 Python代码?
- 2024-10-31 Python集成ActiveMQ,异步发送处理消息,详细代码手把手操作
- 2024-10-31 python 魔法方法连载三 __setattr()__
- 2024-10-31 CentOS 7下编译安装Python3 centos7安装python3.7
- 2024-10-31 3分钟掌握Python 中的集合 python中集合的概念
- 2024-10-31 Python3 集合 python 集合 discard
- 2024-10-31 群晖安装python3 群晖安装python3.7
- 2024-10-31 Python的设计还是很精妙的,三分钟理解__get__和__set__
- 2024-10-31 十六、Python集合set常用方法 python set集合和list集合的区别
- 2024-10-31 python数据类型-集合set python set集合取值
- 最近发表
- 标签列表
-
- jsp (69)
- gitpush (78)
- gitreset (66)
- python字典 (67)
- dockercp (63)
- gitclone命令 (63)
- dockersave (62)
- linux命令大全 (65)
- pythonif (86)
- location.href (69)
- dockerexec (65)
- tail-f (79)
- queryselectorall (63)
- location.search (79)
- bootstrap教程 (74)
- 单例 (62)
- linuxgzip (68)
- 字符串连接 (73)
- html标签 (69)
- c++初始化列表 (64)
- mysqlinnodbmyisam区别 (63)
- arraylistadd (66)
- mysqldatesub函数 (63)
- window10java环境变量设置 (66)
- c++虚函数和纯虚函数的区别 (66)