1.集合的用处就是唯一,会自动将集合里的重复值删除,例如>>> num2 = {1,2,3,4,5,5,4,3,2}
>>> num2
{1, 2, 3, 4, 5};
2.集合不可以使用位置索引来查询值;
3.创建集合有两种办法,第一种用花括号创建类似上1.,第二种是使用set()函数,>>> set1 = set([1,2,3,4,5])
>>> set1
{1, 2, 3, 4, 5}
>>> type(set1)
<class 'set'>,set()函数的参数也是唯一,可以是列表、元组、字符串;
4.集合有助于去除列表(或其他序列)的重复元素,举例一,不使用集合的做法,
>>> num1={1,2,3,4,5,3,1,0}
>>> temp=[]
>>> for each in num1:
if each not in temp:
temp.append(each)
>>> temp
[0, 1, 2, 3, 4, 5]
举例二,使用集合的做法:>>> num1=list(set(num1))
>>> num1
[0, 1, 2, 3, 4, 5];
5.可以判断一个元素是否存在在集合中,举例:>>> 1 in num1
True;
6.add():集合添加元素的函数,举例:>>> num2.add(6)
>>> num2
{1, 2, 3, 4, 5, 6};
7.remove():移除集合中的某个元素,举例:>>> num2.remove(6)
>>> num2
{1, 2, 3, 4, 5};
8.不可变集合:使用frozenset()方法,举例:>>> num3 = frozenset([1,2,3,4,5])
>>> num3.add(0)
Traceback (most recent call last):
File "<pyshell#115>", line 1, in <module>
num3.add(0)
AttributeError: 'frozenset' object has no attribute 'add',会报错。