Python 中的集合,和数学中的集合概念一样,用来保存不重复的元素,即集合中的元素都是唯一的,互不相同。
从形式上看,和字典类似,Python 集合会将所有元素放在一对大括号 {} 中,相邻元素之间用“,”分隔,如下所示:
{element1,element2,...,elementn}
其中,elementn 表示集合中的元素,个数没有限制。
从内容上看,同一集合中,只能存储不可变的数据类型,包括整形、浮点型、字符串、元组,无法存储列表、字典、集合这些可变的数据类型,否则 Python 解释器会抛出 TypeError 错误。比如说:
>>> {
{
'a':1}}
Traceback (most recent call last):
File "<pyshell#8>", line 1, in <module>
{
{
'a':1}}
TypeError: unhashable type: 'dict'
>>> {
[1,2,3]}
Traceback (most recent call last):
File "<pyshell#9>", line 1, in <module>
{
[1,2,3]}
TypeError: unhashable type: 'list'
>>> {
{
1,2,3}}
Traceback (most recent call last):
File "<pyshell#10>", line 1, in <module>
{
{
1,2,3}}
TypeError: unhashable type: 'set'
并且需要注意的是,数据必须保证是唯一的,因为集合对于每种数据元素,只会保留一份。例如:
>>> {
1,2,1,(1,2,3),'c','c'}
{
1, 2, 'c', (1, 2, 3)}
由于 Python 中的 s