
回顾
int/float/str/list/tuple/dict
整数型和浮点型是不可变的,不是序列
字符串是不可变的,是序列
列表是可变的,是序列
元组是不可变的,是序列
字典是可变得,但不是序列
集合的基本概念
集合是基本的数学概念,它是集合论的研究对象,指具有某种特定性质的事物的总体,(在最原始的集合论─朴素集合论─中的定义,集合就是“一堆东西”。)集合里的事物(“东西”),叫作元素。若然 x 是集合 A 的元素,记作 x ∈ A。
创建集合的方法
方法1:使用花括号{} ;用花括号所包裹的对象,就是一个集合
方法2:set()函数 一般使用这个函数创建集合
集合的元素没有顺序,不可重复
集合是不可哈希的
>>> {1,"python"} #使用花括号创建集合
set(['python', 1])
>>> type({1,"python"})
<type 'set'>
>>> set("python")
set(['h', 'o', 'n', 'p', 't', 'y'])
>>> s= set("python") #使用set()创建集合
>>> s
set(['h', 'o', 'n', 'p', 't', 'y'])
>>> s2=set(["baidu","google","ali"])
>>> type(s2)
<type 'set'>
>>> s2
set(['baidu', 'google', 'ali']) #集合的元素没有顺序
>>> s3=set([2,2,2,2,2])
>>> s3 #集合元素不可重复
set([2])
>>>
可哈希与不可哈希
就是在其生存期内,不可变的对象,是可哈希的,反之,可变的就是不可哈希的
Python中所有不可变的都是可哈希的,如数字、字符串、元组
另列表、字典都是可变的,都是不可哈希的
在字典中的Key键必须是可哈希的,即不可变的对象
在集合中,集合的元素必须是可哈希的,也就是说集合的元素必须是不可变对象
所以说用列表作为集合的元素,就报错,因为列表是不可哈希的对象
>>> lst =[[1,2,3],"python"] #用列表作为参数,创建一个集合,报错list 是不可hash的
>>> s =set(lst)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'list'
>>> d={[1,2,3]:"python"} #创建一个字典,key为列表,报错list 是不可hash的
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'list' #list 是不可哈希的
>>>
集合与列表之间的转换
set() list()
>>> lst=[1,2,3]
>>> s =set(lst) #将列表转换成集合
>>> s
set([1, 2, 3])
>>> lst2 =list(s) #将集合转换为列表
>>> lst2
[1, 2, 3]
>>> a =[1,2,2,3,3,6,6,8,9,0,0] #去除列表中的重复项,可使用set()集合
>>> s =set(a)
>>> s
set([0, 1, 2, 3, 6, 8, 9])
>>> a =list(s) #去除重复后,再转换为列表list
>>> a
[0, 1, 2, 3, 6, 8, 9]
>>> s
set([0, 1, 2, 3, 6, 8, 9])
>>> hash(s) #返回hash值,也可判断是否可哈希,报错不可哈希,否则返回hash值
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'set'
>>> hash(1)
1
创建不可变集合
frozenset() 创建不可变集合,是可哈希的
>>> a
[0,1,2,3,6,8,9]
>>> s2 =frozenset(a)
>>> type(s2)
<type 'frozenset'>
>>> hash(s2)
2096340863
>>>