python 集合 set

集合(Set)

集合是无序和无索引的集合。在 Python 中,集合用花括号编写。

基础用法

#创建集合  (集合是无序的,因此您无法确定项目的显示顺序。)
thisset={'apple','banana'}
print(thisset)#{'banana', 'apple'}


#for循环遍历集合 并打印值
for x in thisset:
    print(x)

#in 关键字检查子项目是否存在集合中
print('apple' in thisset)#True


#更改项目
#集合一旦创建,您就无法更改项目,但是您可以添加新项目。

# add()方法向集合中添加项目
thisset.add('orange')
print(thisset)#{'orange', 'banana', 'apple'}

# update()方法将多个项添加到集合中
thisset.update(['html','js','jquery'])#将列表 list添加到集合中
thisset.update(('css','andro','java'))#将元组 tuple添加到集合中
print(thisset)#{'css', 'banana', 'html', 'jquery', 'apple', 'orange', 'java', 'andro', 'js'}

#len() 获取set 集合的长度
print(len(thisset))#9



#删除集合中的项目
#remove()  如果项目不存在 remove()将会报错
#discard() 删除项目不存在 也不会报错
# thisset.remove('hahah')#KeyError: 'hahah' 报错
thisset.remove('apple');
print(thisset)#{'jquery', 'java', 'banana', 'orange', 'andro', 'html', 'js', 'css'}
thisset.discard('html')
print(thisset)#{'js', 'andro', 'banana', 'orange', 'jquery', 'css', 'java'}
thisset.discard('hahah')
print(thisset)#{'jquery', 'css', 'banana', 'js', 'andro', 'orange', 'java'}


#pop() 方法 可以删除集合中的最后一项  因为集合石无序的 因此您不会知道被删除的是什么项目。
#pop() 方法的返回值是被删除的项目。所以无法确认被删除的项,
E=thisset.pop()
print(E)#随机删除一项

#clear() 方法  清空集合 
thisset.clear()
print(thisset)#set()

#del 关键字 彻底删除集合
del thisset
print(thisset)# 报错 NameError: name 'thisset' is not define
View Code

和并集合

#合并两个集合
#在 Python 中,有几种方法可以连接两个或多个集合。

#union() 方法返回一个新集合,其中包括两集合中的所有项目
set1=set(('apple','blue'))
set2=set(('orange','yello'))
set3=set1.union(set2)
print(set3)#{'apple', 'orange', 'yello', 'blue'}

#使用update() 方法将一个集合插入到另外一个集合中
set1.update(set2)
print(set1)#{'yello', 'orange', 'apple', 'blue'}


#set() 构造函数 生成一个集合
set5=(['1','bnana'])
print(set5)#['1', 'bnana']
View Code

原文地址:https://www.cnblogs.com/lvlisn/p/15121457.html