重庆分公司,新征程启航

为企业提供网站建设、域名注册、服务器等服务

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

本文小编为大家详细介绍“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和创建对象的复制方法是什么”文章已经介绍完毕,想要掌握这篇文章的知识点还需要大家自己动手实践使用过才能领会,如果想了解更多相关内容的文章,欢迎关注创新互联行业资讯频道。


网页名称:python集合set和创建对象的复制方法是什么
本文网址:http://cqcxhl.com/article/jppips.html

其他资讯

在线咨询
服务热线
服务热线:028-86922220
TOP