数据类型(集合)

集合(set){}
       空的时候是默认为字典,有值就是集合
python

数学概念:由一个或多个肯定的元素所构成的总体叫作集合。app

特征iphone

1.肯定性(元素必须可hash)测试

2.互异性(去重)spa

3.无序性(集合中的元素没有前后之分),如集合{3,4,5}和{3,5,4}算做同一个集合。code

做用:blog

去重 把一个列表变成集合,就自动去重了ip

关系测试 测试两组数据之间的交集、差集和并集rem


关系运算数学

&.&=:交集

iphone7 = {"lily","jack","peiqi","shanshan"}
iphone8 = {"rose","nicole","lily","shanshan","lucy"}
print(iphone7 & iphone8)#交集  

输出

{'lily', 'shanshan

|,|=:并集

|
set1.union(set2)

iphone7 = {"lily","jack","peiqi","shanshan"}
iphone8 = {"rose","nicole","lily","shanshan","lucy"}
print(iphone7|iphone8)#并集
#or
print(iphone7.union(iphone8))#并集

  输出

{'nicole', 'lucy', 'shanshan', 'peiqi', 'lily', 'rose', 'jack'}
{'nicole', 'lucy', 'shanshan', 'peiqi', 'lily', 'rose', 'jack'}

-,-=:差集 (只iphone7,而没有iphone8)

set1.difference(set2)

iphone7 = {"lily","jack","peiqi","shanshan"}
iphone8 = {"rose","nicole","lily","shanshan","lucy"}
#print(iphone7 - iphone8)#差集
#or
print(iphone7.difference(iphone8))

  输出

{'jack', 'peiqi'}

 
 

^,^=:对称差集(只iphone7oriphone8)

^

set1.symmetric_difference(set2

iphone7 = {"lily","jack","peiqi","shanshan"}
iphone8 = {"rose","nicole","lily","shanshan","lucy"}
print(iphone7^iphone8)#对称差集
#or
print(iphone7.symmetric_difference(iphone8))#对称差集

  输出

{'nicole', 'rose', 'lucy', 'jack', 'peiqi'}
{'nicole', 'rose', 'lucy', 'jack', 'peiqi'}

包含关系

in,not in:判断某元素是否在集合内
==,!=:判断两个集合是否相等

两个集合之间通常有三种关系,相交、包含、不相交。在Python中分别用下面的方法判断:

  • set1.isdisjoint(set2):判断两个集合是否是不相交
  • set1.issuperset(set2):判断集合是否是包含其余集合,等同于a>=b
  • set1.issubset(set2):判断集合是否是被其余集合包含,等同于a<=b
  • se1t.difference_update(set2) :把差集的结果赋给set1
  • set1.intersection_update(set2):把交集的结果赋给set1

集合的经常使用操做

列表(元组)转成集合

l = [1,2,3,4,5,6,7,8]
print(type(l))
n = set(l)#转成集合
print(type(n))

  输出

<class 'list'>
<class 'set'>

增长

单个元素的增长 : set.add(),add的做用相似列表中的append

对序列的增长 : set.update(),update方法能够支持同时传入多个参数,将两个集合链接起来:

s = {1,2}
s.add(3)#单个增长
print(s)
s.update([4,5],[3,6,7])#能够传入多个数据
print(s)

  输出

{1, 2, 3}
{1, 2, 3, 4, 5, 6, 7}

删除

set.discard(x)不会抛出异常

set.remove(x)会抛出KeyError错误  #想删谁,括号里写谁

set.pop():因为集合是无序的,pop返回的结果不能肯定,且当集合为空时调用pop会抛出KeyError错误,

set.clear():清空集合

s = {1,2,3,4,5,6,7,8,9}
s.discard(10)
print(s)
s.discard(10)#删除指定一个
print(s)
s.pop()#随机删除一个
print(s)
s.clear()#清空
print(s)

  输出

{1, 2, 3, 4, 5, 6, 7, 8, 9}{1, 2, 3, 4, 5, 6, 7, 8, 9}{2, 3, 4, 5, 6, 7, 8, 9}set()

相关文章
相关标签/搜索