python3set(集合)详解

add(增加元素)

name = set([‘tom’,’lucy’,’ben’])
name.add(‘juny’)print(name)#输出:{‘lucy’, ‘juny’, ‘ben’, ‘tom’}

clear(清空所有元素)

name = set([‘tom’,’lucy’,’ben’])
name.clear()print(name)#输出:set()

copy(拷贝set集合)

name = set([‘tom’,’lucy’,’ben’])
new_name = name.copy()print(new_name)#输出:{‘tom’, ‘lucy’, ‘ben’}

difference(返回两个或多个集合中不同的元素,并生成新的集合)

a = set([2,3,4,5])
b = set([3,4])
c = set([2])
n = n1.difference(n2,n3)
print(n)
#输出:{5}
#返回a集合里面,在b和c集合中没有的元素,并生成新的集合

difference_update(删除a集合里面,在b集合中存在的元素。)

a = set([2,3,4,5])
b = set([4,5])
a.difference_update(b)
print(a)
#输出:{2, 3}

discard(移除元素)

n = set([2,3,4])
n.discard(3)print(n)#输出:{2, 4}

intersection(取交集,并生成新的集合)

n1 = set([2,3,4,5])
n2 = set([4,5,6,7])
n = n1.intersection(n2)print(n)#输出:{4, 5}

intersection_update(取交集,修改原来的集合)

n1 = set([2,3,4,5])
n2 = set([4,5,6,7])
n1.intersection_update(n2)print(n1)#输出:{4, 5}

isdisjoint(判断交集,是返回false,否返回true)

n1 = set([2,3,4,5])
n2 = set([4,5,6,7])print(n1.isdisjoint(n2))#输出:false

issubset(判断子集)

a = set([2,3])
b = set([2,3,4,5])print(a.issubset(b))#输出:true#a是b的子集

issuperset(判断父集)

a = set([2,3])
b = set([2,3,4,5])print(b.issuperset(a))# 输出:true#b是a的父集

pop(随机移除一个元素)

n = set([2,3,4,5])
n1 = n.pop()print(n,n1)# 输出:{3, 4, 5} 2

remove(移除指定元素)

n = set([2,3,4,5])
n.remove(2)print(n)# 输出:{3, 4, 5}

symmetric_difference(取交集,并生成新的集合)

a = set([2,3,4,5])
b = set([4,5,6,7])print(a.symmetric_difference(b))# 输出:{2, 3, 6, 7}

symmetric_difference_update(取交集,改变原来的集合)

a = set([2,3,4,5])
b = set([4,5,6,7])
a.symmetric_difference_update(b)print(a)# 输出:{2, 3, 6, 7}

union(取并集,并生成新的集合)

a = set([2,3,4,5])
b = set([4,5,6,7])print(a.union(b))# 输出:{2, 3, 4, 5, 6, 7}

update(取并集,改变原来的集合)

a = set([2,3,4,5])
b = set([4,5,6,7])
a.update(b)print(a)# 输出:{2, 3, 4, 5, 6, 7}

以上就是python3 set(集合)详解的详细内容,更多请关注 第一php社区 其它相关文章!

Posted in 未分类