溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

python如何實(shí)現(xiàn)集合的增刪改操作

發(fā)布時(shí)間:2022-03-31 10:33:39 來源:億速云 閱讀:318 作者:小新 欄目:開發(fā)技術(shù)

這篇文章主要為大家展示了“python如何實(shí)現(xiàn)集合的增刪改操作”,內(nèi)容簡(jiǎn)而易懂,條理清晰,希望能夠幫助大家解決疑惑,下面讓小編帶領(lǐng)大家一起研究并學(xué)習(xí)一下“python如何實(shí)現(xiàn)集合的增刪改操作”這篇文章吧。

集合的增刪改

add 函數(shù)

add 函數(shù)的功能:用于集合中添加一個(gè)元素,如果集合中已經(jīng)存在該被添加的元素,則該函數(shù)不執(zhí)行。

add 函數(shù)的用法:set.add(item) ;item 為要被添加到集合的元素;無返回值。

示例如下:

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

# 執(zhí)行結(jié)果如下:
# >>> {'sex', 'birthday', 'age', 'name'}	已存在的 'name' 元素,未再次執(zhí)行添加

update 函數(shù)

update 函數(shù)的功能:在集合中加入一個(gè)新的集合(或者列表、元組、字符串),如果新集合內(nèi)的元素在原集合中存在則無視。

update 函數(shù)的用法:set.update(iterable) ;iterable為集合、列表、元組、字符串;無返回值,直接作用于原集合。

示例如下:

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

# 執(zhí)行結(jié)果如下:
# >>> {'birthday', 'age', 'name'}		列表的成員(元素)被添加進(jìn)集合


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

# 執(zhí)行結(jié)果如下:
# >>> {'name', 'birthday', 'age', 888, 666}		元組的成員(元素)被添加進(jìn)集合


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

# 執(zhí)行結(jié)果如下:
# >>> {'name', 'N', 'birthday', 'e', 'age', 'o', 888, 666}		字符串是每個(gè)字符都作為元素被添加進(jìn)集合的

remove 函數(shù)

remove函數(shù)的功能:將集合中某個(gè)元素刪除,如果該元素不存在則會(huì)報(bào)錯(cuò)。

remove函數(shù)的用法:set.remove(item) ;item 為當(dāng)前集合中的一個(gè)元素;無返回值,直接作用于原集合。

需要注意的是,item 為集合中的某一個(gè)元素,而不是索引。

示例如下:

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

# 執(zhí)行結(jié)果如下:
# >>> {'name', 'birthday', 'age'}


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

# 執(zhí)行結(jié)果如下:
# >>> {'birthday', 'name'}


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

# 執(zhí)行結(jié)果如下:
# >>> KeyError: 'test'		'test'元素不存在則報(bào)錯(cuò)。

clear 函數(shù)

clear 函數(shù)的功能:清空當(dāng)前集合中所有的元素

clear 函數(shù)的用法:set.clear() ;無返回值,直接作用于原集合。

示例如下:

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

print(test_set)

# 執(zhí)行結(jié)果如下:
# >>> set()

del 方法刪除集合

del 的功能:直接刪除 (作用于集合,無法通過索引刪除)

示例如下:

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

# 執(zhí)行結(jié)果如下:
# >>> {'birthday', 'age', 'name'}

del test_set
print(test_set)

# 執(zhí)行結(jié)果如下:
# >>> NameError: name 'test_set' is not defined.

以上是“python如何實(shí)現(xiàn)集合的增刪改操作”這篇文章的所有內(nèi)容,感謝各位的閱讀!相信大家都有了一定的了解,希望分享的內(nèi)容對(duì)大家有所幫助,如果還想學(xué)習(xí)更多知識(shí),歡迎關(guān)注億速云行業(yè)資訊頻道!

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI