set
- 概述:类似dict,是一组key的集合,不存储value
- 本质:无序和无重复元素的集合
创建
- 创建set需要一个list或者tuple或者dict作为输入集合
- 重复元素在set中自动被过滤
s1 = set([1, 2, 3])
s2 = set((5, 6, 7))
s3 = set({"mfq": 24, "zhx": 23})
print(s1)
print(type(s1))
print(s2)
print(type(s2))
print(s3)
print(type(s3))
s4 = set([1, 2, 3, 1, 2, 4])
print(s4)
'''结果为:
{1, 2, 3}
<class 'set'>
{5, 6, 7}
<class 'set'>
{'zhx', 'mfq'}
<class 'set'>
{1, 2, 3, 4}
'''
添加
方式1:set.add()
s1 = set([1, 2, 3])
print(s1)
s1.add(4)
print(s1)
s1.add(3)
print(s1)
s1.add((8, 9, 0))
print(s1)
'''结果为:
{1, 2, 3}
{1, 2, 3, 4}
{1, 2, 3, 4}
{1, 2, 3, 4, (8, 9, 0)}
'''
方式2:set.update()
s1 = set([1, 2, 3])
print(s1)
s1.update([4, 5, 6])
print(s1)
s1.update((7, 8))
print(s1)
s1.update("you are a good man")
print(s1)
s1.update({"mfq": 23})
print(s1)
'''结果为:
{1, 2, 3}
{1, 2, 3, 4, 5, 6}
{1, 2, 3, 4, 5, 6, 7, 8}
{1, 2, 3, 4, 5, 6, 7, 8, 'e', 'g', 'r', ' ', 'n', 'm', 'd', 'o', 'u', 'a', 'y'}
{1, 2, 3, 4, 5, 6, 7, 8, 'e', 'g', 'mfq', 'r', ' ', 'n', 'm', 'd', 'o', 'u', 'a', 'y'}
'''
删除
s1 = set([1, 2, 3])
print(s1)
s1.remove(2)
print(s1)
'''结果为:
{1, 2, 3}
{1, 3}
'''
遍历
s1 = set([1, 2, 3, 4, 5])
for i in s1:
print(i)
for index, data in enumerate(s1):
print(index, data)
'''结果为:
1
2
3
4
5
0 1
1 2
2 3
3 4
4 5
'''
交集&、并集|
s1 = set([1, 2, 3, 4, 5])
s2 = set([4, 5, 6, 7, 8])
s3 = s1 & s2
print(s3)
print(type(s3))
s4 = s1 | s2
print(s4)
print(type(s4))
'''结果为:
{4, 5}
<class 'set'>
{1, 2, 3, 4, 5, 6, 7, 8}
<class 'set'>
'''
类型转换
- list—>set
- tuple—>set
- set—>list
s1 = {1, 2, 3, 4, 5}
print(s1)
list1 = list(s1)
print(list1)
'''结果为:
{1, 2, 3, 4, 5}
[1, 2, 3, 4, 5]
'''
s1 = {1, 2, 3, 4, 5}
print(s1)
tuple1 = tuple(s1)
print(tuple1)
'''结果为:
{1, 2, 3, 4, 5}
(1, 2, 3, 4, 5)
'''