集合中的元素具有唯一性。
>>> num2 = {1, 2, 3} #{}没有体现出映射关系就是集合
>>> type(num2)
<class 'set'>
>>> num2 = {1, 2, 3, 3, 4, 4} #自动剔除重复元素
>>> num2
{1, 2, 3, 4}
>>> num2 = {1, 2, 3, 3, 4, 4}
>>> num2
{1, 2, 3, 4}
>>> num2[2]
Traceback (most recent call last):
File "<pyshell#16>", line 1, in <module>
num2[2]
TypeError: 'set' object does not support indexing
创建集合:
①把一列元素用花括号括起来
②使用工厂函数set()
>>> help(set)
Help on class set in module builtins:
class set(object)
| set() -> new empty set object
| set(iterable) -> new set object
|
| Build an unordered collection of unique elements.
>>> set1 = set([1, 2, 3, 4, 4])
>>> set1
{1, 2, 3, 4}
习题:去掉列表[0, 1, 2, 3, 4, 5, 5, 3, 1]中重复的元素
>>> num1 = [0, 1, 2, 3, 4, 5, 5, 3, 1]
>>> 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]
不可变集合:frozenset
>>> num3 = frozenset([1, 2, 3])
>>> num3.add(4)
Traceback (most recent call last):
File "<pyshell#33>", line 1, in <module>
num3.add(4)
AttributeError: 'frozenset' object has no attribute 'add'