色破飞机 发表于 2018-8-16 08:27:09

python中set集合常用方法

  今天开始学习python的集合相关方法的使用:
  #集合的定义:集合是无序的,不重复的数据集合
set={"123","456","11"}  #add:向集合中填加元素
Add an element to a set.set.add(563)  
print(set)
  #Clear:清除集合中的元素
  Remove all elements from this set.
set.clear()  
print(set)返回空
  #Copy:复制一个集合并赋值给一个新的集合
  set3=set2.copy()
  #difference():打印set中和set2不一样的元素
set3=set.difference(set2)  
print(set3)
  #different_update():把集合set中和set2不一样的元素取出来并且更新到set里面
Remove all elements of another set from this set.set.difference_update(set2)  
print(set)
  #discard():如果一个元素属于该集合则删除,如果不属于该集合则什么也不做
Remove an element from a set if it is a member.  
If the element is not a member, do nothing.
  
set.discard("1234")
  
print(set)
  
Remove an element from a set; it must be a member.
  
If the element is not a member, raise a KeyError.
  
set.remove("123")
  
print(set)
  #pop():随机删除集合里面的元素,如果集合为空则报错,建议使用discard
Remove and return an arbitrary set element.  
Raises KeyError if the set is empty.
  
set.pop("11")
  
print(set)
  # Intersection:将set和set2两个集合的交集放入集合3并打印。
Return the intersection of two sets as a new set.set3=set.intersection(set2)  
print(set3)
  #intersection_update():将set和set2两个集合的交集更新到set中。
Update a set with the intersection of itself and another.set.intersection_update(set2)  
print(set)
  #isdisjoint():如果两个集合没有交集则返回true,反之如果有交集则返回false。
Return True if two sets have a null intersectionset3=.isdisjoint(set2)  
(set3)
  #issubset():set是否是set2的子集,如果是返回True,否则返回false
Report whether another set contains this set.set3=set.issubset(set2)  
print(set3)
  #issuperset():set是否是set2的父集,如果是则返回True,如果不是则返回False.
Report whether this set contains another set.set3=set.issuperset(set2)  
print(set3)
  #symmetric_difference():将两个集合中不是交集的部分取出来
Return the symmetric difference of two sets as a new set.set3=set.symmetric_difference(set2)  
print(set3)
  #symmetric_difference_update():取出set集合set2集合不是交集的部分,并且把值更新到set集合。
Update a set with the symmetric difference of itself and another..symmetric_difference_update(set2)  
()
  #union():取两个集合的合集,把所有元素汇集在一起形成新的集合,但是元素不重复
Return the union of sets as a new set=set.union(set2)  
(set)
  #update():把一个集合和另一个集合的合集更新到当前集合中,当前集合之前的数据被覆盖。
Update a set with the union of itself and others..update(set2)  
()
  上面就是所有关于集合的方法了,终于听完课以后自己把所有的方法都实验完了。
页: [1]
查看完整版本: python中set集合常用方法