今天说以个很有意思的结构,也就是python 中的set结构,为什么说set结构是一个很有意思的结构,接下来大家看了就知道了。
num={}
In [11]: type(num)
Out[11]: dict
In [12]: num2={1,2,3,4,5,6,7,8,9}
In [13]: type(num2)
Out[13]: set
有意思的地方之一,当对num进行赋值的时候采用{}空花括号进行赋值,类型是字典,但是进行相应的数据进行赋值的时候,得到的就是set类型的数据,也就是变成了集合的类型。
In [19]: #在不运用集合特性的情况下怎样进行数据的去重
In [21]: num1=[1,2,3,4,5,6,7,8,9,4,5,6,3,2,1,7,8,9]
In [24]: temp=[]
In [25]: for each in num1:
...: if each not in temp:
...: temp.append(each)
...:
In [26]: temp
Out[26]: [1, 2, 3, 4, 5, 6, 7, 8, 9]
可以看到在没有运 运用到集合特性的时候想去除数组中的重复元素相当的麻烦!
#在集合中添加元素
In [28]: temp.add(10)
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-28-dfe6d3c81c55> in <module>()
----> 1 temp.add(10)
AttributeError: 'list' object has no attribute 'add'
In [29]: num1={1,2,3,4,5,6,7,8,9,4,5,6,3,2,1,7,8,9}
In [30]: num1
Out[30]: {1, 2, 3, 4, 5, 6, 7, 8, 9}
In [31]: num1.add(10)
In [32]: num1
Out[32]: {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
In [33]: num.remove(3)
In [34]: num1
Out[34]: {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
In [35]: num1.remove(3)
In [36]: num14
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-36-8faac97b74a3> in <module>()
----> 1 num14
NameError: name 'num14' is not defined
In [37]: num1
Out[37]: {1, 2, 4, 5, 6, 7, 8, 9, 10}
本文介绍了 Python 中 set 结构的特点及应用,通过对比字典初始化方式的区别,展示 set 如何实现数据去重,并演示如何使用 add 和 remove 方法来操作集合元素。
3348

被折叠的 条评论
为什么被折叠?



