集合是无序的,不重复的数据集合,它里面的元素是可哈希的(不可变类型),但是集合本身是不可哈希(所以集合做不了字典的键)的。

以下是集合最重要的两点:

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

  关系测试,测试两组数据之前的交集、差集、并集等关系。

创建集合

set1 = set([1,2,3])
print(set1)
set2 = {1,2,3,[2,3],{'name':'alex'}}  #错的
print(set2)

set1 = {'alex','wusir','ritian','egon','barry'}
set1.add('tim')
print(set1)


{'barry', 'tim', 'egon', 'alex', 'ritian', 'wusir'}
set1.update('abc')
print(set1)

{'c', 'b', 'a', 'wusir', 'ritian', 'alex', 'egon', 'barry'}

set1.pop()    #随机删除,有返回值
print(set1)     


{'wusir', 'ritian', 'alex', 'barry'}
set1.remove('alex')   #按元素删除
print(set1)


{'ritian', 'barry', 'wusir', 'egon'}
set1.clear()   #清空列表
print(set1)


set()
del set1   #删除整个集合
print(set1)

   print(set1)
NameError: name 'set1' is not defined

 循环

for i in set1:
    print(i)


wusir
alex
egon
ritian
barry

求交集

set1 = {1,2,3,4,5}
set2 = {4,5,6,7,8}
print(set1 & set2)  # {4, 5}
print(set1.intersection(set2))  # {4, 5}

{4, 5}
{4, 5}

并集

set1 = {1,2,3,4,5}
set2 = {4,5,6,7,8}
print(set1 | set2)  # {1, 2, 3, 4, 5, 6, 7,8}
print(set2.union(set1))  # {1, 2, 3, 4, 5, 6, 7,8}


{1, 2, 3, 4, 5, 6, 7, 8}
{1, 2, 3, 4, 5, 6, 7, 8}
#反交集
set1 = {1,2,3,4,5}
set2 = {4,5,6,7,8}
print(set1 ^ set2)  # {1, 2, 3, 6, 7, 8}
print(set1.symmetric_difference(set2))  # {1, 2, 3, 6, 7, 8}


{1, 2, 3, 6, 7, 8}
{1, 2, 3, 6, 7, 8}
#差集
set1 = {1,2,3,4,5}
set2 = {4,5,6,7,8}
print(set1 - set2)  # {1, 2, 3}  set1独有的
print(set2 - set1)  # {6, 7, 8}  set2独有的
print(set1.difference(set2))  # {1, 2, 3}


{1, 2, 3}
{8, 6, 7}
{1, 2, 3}
子集与超集
set1 = {1,2,3}
set2 = {1,2,3,4,5,6}

print(set1 < set2)
print(set1.issubset(set2))  # 这两个相同,都是说明set1是set2子集。

print(set2 > set1)
print(set2.issuperset(set1))  # 这两个相同,都是说明set2是set1超集。

True
True
True
True

列表和集合转换和去重

li = {1,23,44,44,1,4,5,6,6}
set1 = set(li)
print(set1)
li = list(set1)
print(li)

{1, 4, 5, 6, 23, 44}
[1, 4, 5, 6, 23, 44]

 集合变成不可变类型

s = frozenset('barry')  #frozenset不可变集合,让集合变成不可变类型
print(s,type(s))  # frozenset({'a', 'y', 'b', 'r'}) <class 'frozenset'>

 循环

s = frozenset('barry')
for i in s:
    print(i)

a
y
b
r

 

posted on 2019-01-03 14:03  Tim-code  阅读(252)  评论(0编辑  收藏  举报