溫馨提示×

溫馨提示×

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

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

python集合set和創(chuàng)建對象的復(fù)制方法是什么

發(fā)布時間:2022-01-13 14:51:53 來源:億速云 閱讀:200 作者:iii 欄目:大數(shù)據(jù)

本文小編為大家詳細(xì)介紹“python集合set和創(chuàng)建對象的復(fù)制方法是什么”,內(nèi)容詳細(xì),步驟清晰,細(xì)節(jié)處理妥當(dāng),希望這篇“python集合set和創(chuàng)建對象的復(fù)制方法是什么”文章能幫助大家解決疑惑,下面跟著小編的思路慢慢深入,一起來學(xué)習(xí)新知識吧。

集合set

輸入:

bri = set(['brazil', 'russia', 'india'])

print('india' in bri) 


print('usa' in bri )


bric = bri.copy() 

bric.add('china') 

print( bric.issuperset(bri) )


bri.remove('russia') 

print( bri & bric )

# OR bri.intersection(bric) 

輸出:

True

False

True

{'brazil', 'india'}

解釋:

集合集是簡單對象的無序集合。集合相比與順序性的數(shù)據(jù)結(jié)構(gòu),更注重與集合中的對象是否存在,以及發(fā)生多少次。

本例中,首先定義了set集合名為bri.

然后使用in語句來判斷'india','usa',兩個對象是否在集合中,輸出結(jié)果會根據(jù)對象是否在集合中,返回bool值 TRUE 或者 False 。

集合有copy()函數(shù),可以復(fù)制出一份新的集合。

集合可以調(diào)用.remove() 來刪除其中的某個對象。

可以進(jìn)集合運算,本例中進(jìn)行取交集運算。

輸出結(jié)果為:{'brazil', 'india'}

創(chuàng)建對象的復(fù)制操作

輸入:

#!/usr/bin/python 

# Filename: reference.py 


print('Simple Assignment') 

shoplist = ['apple', 'mango', 'carrot', 'banana']mylist = shoplist 

# mylist is just another name pointing to the sameobject! 


del shoplist[0] 

# I purchased the first item, so I remove it from thelist 


print('shoplist is', shoplist) 

print('mylist is', mylist) 

# notice that both shoplist and mylist both print the same list without 

# the 'apple' confirming that they point to the same object 


print('Copy by making a full slice') 

mylist = shoplist[:] # make a copy by doing a full slice 


del mylist[0] 

# remove first item 

print('shoplist is', shoplist) 

print('mylist is', mylist) 

# notice that now the two lists are different

輸出:

$ python reference.py 

Simple Assignment 

 shoplist is ['mango', 'carrot', 'banana'] 

 mylist is ['mango', 'carrot', 'banana'] 

 Copy by making a full slice 

 shoplist is ['mango', 'carrot', 'banana'] 

 mylist is ['carrot', 'banana']

解釋:

當(dāng)你創(chuàng)建對象并將其分配給變量時,該變量僅引用該對象,并不代表對象本身!可以理解為分配了一個地址鏈接。

本例中舉了兩組例子。

首先建立一個列表shoplist,我們在拷貝復(fù)制出一個列表mylist。 拷貝方式使用 “=” 賦值。

我們刪除 shoplist中的一個元素,發(fā)現(xiàn)mylist中的元素也被刪除了。

第二次,我們同樣拷貝復(fù)制出一個列表mylist。 拷貝方式使用 “mylist = shoplist[:]” 賦值。

我們刪除 shoplist中的一個元素,發(fā)現(xiàn)mylist中的元素還存在。

第一中,方式我們只復(fù)制出來對象的地址映射,而第二次,我們完整的賦值了對象的內(nèi)容。

讀到這里,這篇“python集合set和創(chuàng)建對象的復(fù)制方法是什么”文章已經(jīng)介紹完畢,想要掌握這篇文章的知識點還需要大家自己動手實踐使用過才能領(lǐng)會,如果想了解更多相關(guān)內(nèi)容的文章,歡迎關(guān)注億速云行業(yè)資訊頻道。

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

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

AI