这几天有很多事情,Python学习拉下了很多,所以这里我就简单写一下Python中的集合吧。
集合和字典一样都是使用的大括号{},但字典大括号中有冒号,集合中没有,然后空的大括号默认为字典,如这样:
>>>num1={} >>>num2={1,2,3,4,5} >>>num3={'A':'a','B':'b'}
>>>type(num1) >>>type(num2) >>>type(num3)
<class 'dict'> <class 'set'> <class 'dict'>
set也可以创建集合,格式为 >>> 集合名=set([ ]),( )中可以是( )[ ]{ }。如:
>>>a=set((1,2,3,4,5)) >>>a=set([1,2,3,4,5]) >>>a=set({1,2,3,4,5})
>>>a >>>a >>>a
{1,2,3,4,5} {1,2,3,4,5} {1,2,3,4,5}
>>>type(a) >>>type(a) >>>type(a)
<class 'set'> <class 'set'> <class 'set'>
集合中需要注意的是集合中的值是唯一的:
>>> num={1,2,3,4,5,4,3,2,1}
>>> num
{1, 2, 3, 4, 5}
还有集合不支持索引:
>>> num={1,2,3,4,5}
>>> num[2]
Traceback (most recent call last):
File "<pyshell#3>", line 1, in <module>
num[2]
TypeError: 'set' object does not support indexing
集合中的两个简单操作符add和remove,add:用法是 >>>num.add(),它的用途是把括号里的元素添加到集合中,添加重复的不会报错,一次只能添加一个元素;remove:用法是>>>num.remove(),它是移除集合中的元素,如果移除集合中没有的元素会报错,一次只能移除一个。
frozenset:frozenset是冻结的集合,它是不可变的,好处是它可以作为字典的key,也可以作为其它集合的元素。缺点是一旦创建便不能更改,没有add,remove方法。如:
>>> num=frozenset([1,2,3])
>>> num.add(4)
Traceback (most recent call last):
File "<pyshell#6>", line 1, in <module>
num.add(4)
AttributeError: 'frozenset' object has no attribute 'add'
>>> num.remove(1)
Traceback (most recent call last):
File "<pyshell#7>", line 1, in <module>
num.remove(1)
AttributeError: 'frozenset' object has no attribute 'remove'
集合就介绍到这里吧。欢迎补充!