Python入门——Day7(集合,不可变集合,访问集合)

0.目录

1.什么是集合?
2.去除重复元素
3.访问集合中的值
4.不可变集合

1.集合

  • 如何创建一个集合:
    1.一种是直接把一堆元素用花括号括起来
    2.一种是使用set()工厂函数
>>> num = {}
>>> type(num)
<class 'dict'>
>>> num = {1,2,3,4,5}#集合
>>> type(num)
<class 'set'>
这里我们可以看出,({})花括号不是字典的专属

>>> set1 = set([1,2,3,4,5,6,5])
>>> set1
{1, 2, 3, 4, 5, 6}

>>> num2 = {1,2,3,4,5,6,4,2,1}
>>> num2
{1, 2, 3, 4, 5, 6}
集合会自动筛选去除重复元素

集合中的元素没有位置,不能通过索引获取
>>> num[2]
Traceback (most recent call last):
  File "<pyshell#104>", line 1, in <module>
    num[2]
TypeError: 'set' object is not subscriptable

2.去除序列中的重复元素

正常写法
>>> num1 = [1,2,3,4,5,4,2,1,0]
>>> temp = []
>>> for each in num1:
	if each not in temp:
		temp.append(each)

		
>>> temp
[1, 2, 3, 4, 5, 0]
集合写法
>>> num1 = list(set(num1))
>>> num1
[0, 1, 2, 3, 4, 5]

3.如何访问集合中的值

  • 可以通过 in 和 not in 判断一个元素是否在集合已经存在
  • 可以用 for 把集合中的元素一个个读取出来
>>> num1
[0, 1, 2, 3, 4, 5]
>>> num2
{1, 2, 3, 4, 5}
>>> 1 in num1
True
>>> 1 in num2
True
>>> '1' in num2
False
>>> num2.add(6)
>>> num2
{1, 2, 3, 4, 5, 6}
>>> num2.remove(5)
>>> num2
{1, 2, 3, 4, 6}

4.不可变集合

frozen:冰冻的,冻结的

>>> num3 = frozenset([1,2,3,4,5,6])
>>> num3,add(0)
#报错 
#不可变函数不可进行任何操作
Traceback (most recent call last):
  File "<pyshell#94>", line 1, in <module>
    num3,add(0)
NameError: name 'add' is not defined
发布了23 篇原创文章 · 获赞 14 · 访问量 710

猜你喜欢

转载自blog.csdn.net/weixin_45253216/article/details/104570028