Python学习笔记——集合

1. 定义

num = {}
print(type(num))
num2 = {1,2,3,4,5}
print(type(num2))


集合的数据是唯一的

# 会自动去除重复数据
num2 = {1,2,3,4,5,5,3,2}
print(num2)
{1, 2, 3, 4, 5}

集合的数据是无序的

# 以下表达会报错
num2[2]

---------------------------------------------------------------------------

TypeError                                 Traceback (most recent call last)

 in ()
----> 1 num2[2]
TypeError: 'set' object does not support indexing

2. set()

# set函数可以传进一个列表、元组、字符串
set1 = set([1,2,3,4,5,5])
print(set1)
{1, 2, 3, 4, 5}

去除列表[0,1,2,3,4,5,5,3,1]中重复的元素

# 利用for循环
num3 = [1,2,3,4,5,5,3,1,0]
temp = []
for each in num3:
    if each not in temp:
        temp.append(each)
print(temp)
[1, 2, 3, 4, 5, 0]
# 利用set函数,但是要注意,使用set可能会改变元素在集合中的位置,如num3中的0
num3 = list(set(num3))
print(num3)
[0, 1, 2, 3, 4, 5]

3. 集合的相关操作

# in 和 not in
print(6 in set1)
print(6 not in set1)
False
True
# add() 和 remove()
set2 = set([1,2,3,4,5,5])
set2.add(6)
print(set2)
set2.remove(5)
print(set2)
{1, 2, 3, 4, 5, 6}
{1, 2, 3, 4, 6}

4. frozenset

# 定义一个不可变的集合,此时集合不可更改,否则会报错
set3 = frozenset([1,2,3,4,5])
set3.add(0)
---------------------------------------------------------------------------

AttributeError                            Traceback (most recent call last)

 in ()
      1 # 定义一个不可变的集合
      2 set3 = frozenset([1,2,3,4,5])
----> 3 set3.add(0)

AttributeError: 'frozenset' object has no attribute 'add'

你可能感兴趣的:(Python学习笔记——集合)