Python collection operation

Feature summary: (it has two types: set()) and frozenset. Main summary set([]) set

1. Stored disordered elements

2. All stored elements are not repeated

Set's api sequence:

  • add (element) Add an element to the collection
  • remove (element) Delete the element in the collection
  • clear() Clear the elements of a collection
  • update() merge a list into the collection
  • union() Take the union of two sets
  • intersection() Take the intersection of two sets
  • difference() Take the difference of two sets
  • issubset Whether a collection contains another collection, returns boolean
  • issuperset Determines whether the elements of a set are in another set, and returns a set that does not contain elements

 

Test Results:

#-*- coding:utf-8 -*-
set1=set("huitao")
print(set1)

#add 增加一个元素到集合
setd=set([1,2,3,4])
setd.add(9)
print(setd)

# remove 从set中删除指定元素
setd.remove(4)
print(setd)

#clear()  清空集合

set1.clear()
print(set1)

#update 用于新增多个元素值,参数为list,就是把list合并到集合
gu=["juju","ma"]
setd.update(gu)
print(setd)



#union  俩个集合的并集
setf=set([2,3])
setg=setd.union(setf)
print(setg)

#intersection 俩个集合的交集
seth=setd.intersection(setf)
print(seth)

#issubset 用法 s1.issubset(s2), 判断s1中的每个元素是否都在s2中,即s1<-s2
ft=setg.issubset(setf)
print(ft)

#issuperset 用法 s1.issuperset(s2), 判断s2中的每个元素是否都在s1中,即s1>=s2
ft=setg.issuperset(setd)
print(ft)

#difference 差集  s1.difference(s2), 返回s1中有s2中没的元素

gh=setd.difference(setf)
print(gh)

 

Guess you like

Origin blog.csdn.net/chehec2010/article/details/115284107