温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

python如何实现集合的增删改操作

发布时间:2022-03-31 10:33:39 来源:亿速云 阅读:311 作者:小新 栏目:开发技术

这篇文章主要为大家展示了“python如何实现集合的增删改操作”,内容简而易懂,条理清晰,希望能够帮助大家解决疑惑,下面让小编带领大家一起研究并学习一下“python如何实现集合的增删改操作”这篇文章吧。

集合的增删改

add 函数

add 函数的功能:用于集合中添加一个元素,如果集合中已经存在该被添加的元素,则该函数不执行。

add 函数的用法:set.add(item) ;item 为要被添加到集合的元素;无返回值。

示例如下:

test_set = {'name', 'age', 'birthday'}
test_set.add('sex')
test_set.add('name')
print(test_set)

# 执行结果如下:
# >>> {'sex', 'birthday', 'age', 'name'}	已存在的 'name' 元素,未再次执行添加

update 函数

update 函数的功能:在集合中加入一个新的集合(或者列表、元组、字符串),如果新集合内的元素在原集合中存在则无视。

update 函数的用法:set.update(iterable) ;iterable为集合、列表、元组、字符串;无返回值,直接作用于原集合。

示例如下:

test_set = set()
test_list = ['name', 'age', 'birthday']
test_set.update(test_list)
print(test_set)

# 执行结果如下:
# >>> {'birthday', 'age', 'name'}		列表的成员(元素)被添加进集合


test_tuple = (666, 888)
test_set.update(test_tuple)
print(test_set)

# 执行结果如下:
# >>> {'name', 'birthday', 'age', 888, 666}		元组的成员(元素)被添加进集合


name = 'Neo'
test_set.update(name)
print(test_set)

# 执行结果如下:
# >>> {'name', 'N', 'birthday', 'e', 'age', 'o', 888, 666}		字符串是每个字符都作为元素被添加进集合的

remove 函数

remove函数的功能:将集合中某个元素删除,如果该元素不存在则会报错。

remove函数的用法:set.remove(item) ;item 为当前集合中的一个元素;无返回值,直接作用于原集合。

需要注意的是,item 为集合中的某一个元素,而不是索引。

示例如下:

test_set = set()
test_list = ['name', 'age', 'birthday']
test_set.update(test_list)
print(test_set)

# 执行结果如下:
# >>> {'name', 'birthday', 'age'}


test_set.remove('age')
print(test_set)

# 执行结果如下:
# >>> {'birthday', 'name'}


test_set_01 = set()
test_set.remove('test')
print(test_set_01)

# 执行结果如下:
# >>> KeyError: 'test'		'test'元素不存在则报错。

clear 函数

clear 函数的功能:清空当前集合中所有的元素

clear 函数的用法:set.clear() ;无返回值,直接作用于原集合。

示例如下:

test_set = set()
test_list = ['name', 'age', 'birthday']
test_set.clear()

print(test_set)

# 执行结果如下:
# >>> set()

del 方法删除集合

del 的功能:直接删除 (作用于集合,无法通过索引删除)

示例如下:

test_set = set()
test_list = ['name', 'age', 'birthday']
test_set.update(test_list)
print(test_set)

# 执行结果如下:
# >>> {'birthday', 'age', 'name'}

del test_set
print(test_set)

# 执行结果如下:
# >>> NameError: name 'test_set' is not defined.

以上是“python如何实现集合的增删改操作”这篇文章的所有内容,感谢各位的阅读!相信大家都有了一定的了解,希望分享的内容对大家有所帮助,如果还想学习更多知识,欢迎关注亿速云行业资讯频道!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI