数据类型(集合)

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

数学概念:由一个或多个确定的元素所构成的整体叫做集合。

特征

1.确定性(元素必须可hash)

2.互异性(去重)

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

作用:

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

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


关系运算

&.&=:交集

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()

原文地址:https://www.cnblogs.com/fantsaymwq/p/9498400.html