Python 集合的增删改

目录

  • 集合的add函数
  • 集合的update函数
  • 集合的remove函数
  • 集合的clear函数
  • 用del删除集合
  • 重要说明

add的功能

  • 用于集合中添加一个元素,如果集合中已存在该元素则该函数不执行

add的用法

  • 用法: set.add(item)
  • 参数: item :要添加到集合中的元素
  • 返回值: 无返回值
In [10]: a_set = set()
In [11]: a_set.add ( 'insane' )
In [12]: a_set
0ut [12]: {'insane'}
# coding:utf-8

a_list = ['python', 'django', 'django', 'flask']

a_set = set()

a_set.add(a_list[0])
a_set.add(a_list[1])
a_set.add(a_list[2])
a_set.add(a_list[-1])
print(a_set)

a_set.add(True)
a_set.add(None)
print(a_set)
{'python', 'django', 'flask'}
{'python', True, 'flask', None, 'django'}

Process finished with exit code 0

update的功能

  • 加入一个新的集合(或列表,元组,字符串),如新集合内的元素在原集合中存在则无视

update的用法

  • 用法∶set.update(iterable)
  • 参数: iterable :集合,列表元组字符串
  • 返回值: 无返回值,直接作用于原集合
In [13]: a_set = set()
In [14]: a_set.update( [3,4,5])
In [15]: a_set
out [15]: {3,4,5}
a_tuple = ('a', 'b', 'c')
a_set.update(a_tuple)
print(a_set)
a_set.update('python')
print(a_set)
{'flask', True, 'django', 'b', None, 'a', 'c', 'python'}
{'flask', True, 'django', 'b', None, 'p', 'n', 'a', 'o', 'h', 'c', 'python', 't', 'y'}

Process finished with exit code 0

remove的功能

  • 将集合中的某个元素删除,如元素不存在将会报错

remove的用法

  • 用法: set.remove(item) #注意是元素不是索引
  • 参数: item :当前集合中的一个元素
  • 返回值: 无返回值,直接作用于原集
In [19]: a_set = {1,2,3}
In [20]: a_set.remove(3)
In [21]: a_set
0ut [21]: {1,2}

clear的功能

  • 清空当前集合中的所有元素

clear的用法

  • 用法: set.clear()
  • 参数: 无
  • 返回值: 无返回值,直接作用于原集合
In [22]: a_set = {1,2,3}
In [23]: a_set.clear()
In [24]: a_set
out[24]: set()

del 删除集合

  • 举例:
a_set = {1,2,3}
del a_set
print(a_set) #报错

重要说明

  • 集合无法通过索引获取元素
  • 集合无获取元素的任何方法
  • 集合只是用来处理列表或元组的一种临时类型,他不适合存储与传输

实战

a_set.remove('python')
print(a_set)

a_set.clear()
print(a_set)

a_set.remove('flask')  # 会报错,因为set已清空,没有flask元素

del a_set
# print(a_set)  # 会报错
{True, 'flask', 'c', 'b', None, 'y', 'django', 'n', 't', 'p', 'h', 'a', 'o'}
set()

Process finished with exit code 0
  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值