python学习 集合set

num={}
type(num)
<class ‘dict’>

num2={1,2,3,4}
type(num2)
<class ‘set’>

#这两个大括号的类型明显不一样

num的类型是字典而num2的类型则是集合

集合

集合具有唯一性

num2={1,2,3,4,5,4,2,1,3}
num2
{1, 2, 3, 4, 5}

集合不会打印重复的东西

集合不支持索引

num2[2]
Traceback (most recent call last):
File “<pyshell#10>”, line 1, in
num2[2]
TypeError: ‘set’ object does not support indexing

创建一个集合

1.直接用花括号括起来

set1={‘星期一’,‘星期二’,‘星期三’,‘星期四’,‘星期五’}
set1
{‘星期三’, ‘星期四’, ‘星期五’, ‘星期二’, ‘星期一’}

2.使用set()工厂函数

a=[‘星期一’,‘星期二’,‘星期三’,‘星期四’,‘星期五’]
set2=set(a)
set2
{‘星期三’, ‘星期四’, ‘星期五’, ‘星期二’, ‘星期一’}

【注】set( )括号中可以是列表 元组或序列

当我们需要去除列表元组中重复的元素,可以有如下写法

1.不使用集合set时

num1
[1, 2, 3, 4, 5, 6, 3, 4, 1]

temp
[]

for each in num1:
if each not in temp:
temp.append(each)

temp
[1, 2, 3, 4, 5, 6]

2.使用set

num1
[1, 2, 3, 4, 5, 6, 3, 4, 1]

num1=list(set(num1))
num1
[1, 2, 3, 4, 5, 6]

【注】set是集合,其中的元素是无序的,在需要特定顺序时不可以用set

访问集合中的值
1.使用for读取

2.通过in和not in判断

1 in num1
True

7 in num1
False

向集合中添加和删除元素

num1= set(list(num1))
num1
{1, 2, 3, 4, 5, 6}

num1.add(7)
num1
{1, 2, 3, 4, 5, 6, 7}

num1.remove(1)
num1
{2, 3, 4, 5, 6, 7}

不可变集合frozenset

num3=frozenset([1,2,3])
num3
frozenset({1, 2, 3})

num3.add(4)
Traceback (most recent call last):
File “<pyshell#53>”, line 1, in
num3.add(4)
AttributeError: ‘frozenset’ object has no attribute ‘add’

num3.remove(1)
Traceback (most recent call last):
File “<pyshell#54>”, line 1, in
num3.remove(1)
AttributeError: ‘frozenset’ object has no attribute ‘remove’

不可以改变集合中的值

猜你喜欢

转载自blog.csdn.net/IWTK_wcl/article/details/82771512
今日推荐