温馨提示×

温馨提示×

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

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

python集合set和创建对象的复制方法是什么

发布时间:2022-01-13 14:51:53 来源:亿速云 阅读:185 作者:iii 栏目:大数据

本文小编为大家详细介绍“python集合set和创建对象的复制方法是什么”,内容详细,步骤清晰,细节处理妥当,希望这篇“python集合set和创建对象的复制方法是什么”文章能帮助大家解决疑惑,下面跟着小编的思路慢慢深入,一起来学习新知识吧。

集合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'}

解释:

集合集是简单对象的无序集合。集合相比与顺序性的数据结构,更注重与集合中的对象是否存在,以及发生多少次。

本例中,首先定义了set集合名为bri.

然后使用in语句来判断'india','usa',两个对象是否在集合中,输出结果会根据对象是否在集合中,返回bool值 TRUE 或者 False 。

集合有copy()函数,可以复制出一份新的集合。

集合可以调用.remove() 来删除其中的某个对象。

可以进集合运算,本例中进行取交集运算。

输出结果为:{'brazil', 'india'}

创建对象的复制操作

输入:

#!/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']

解释:

当你创建对象并将其分配给变量时,该变量仅引用该对象,并不代表对象本身!可以理解为分配了一个地址链接。

本例中举了两组例子。

首先建立一个列表shoplist,我们在拷贝复制出一个列表mylist。 拷贝方式使用 “=” 赋值。

我们删除 shoplist中的一个元素,发现mylist中的元素也被删除了。

第二次,我们同样拷贝复制出一个列表mylist。 拷贝方式使用 “mylist = shoplist[:]” 赋值。

我们删除 shoplist中的一个元素,发现mylist中的元素还存在。

第一中,方式我们只复制出来对象的地址映射,而第二次,我们完整的赋值了对象的内容。

读到这里,这篇“python集合set和创建对象的复制方法是什么”文章已经介绍完毕,想要掌握这篇文章的知识点还需要大家自己动手实践使用过才能领会,如果想了解更多相关内容的文章,欢迎关注亿速云行业资讯频道。

向AI问一下细节

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

AI