Python学习笔记——集合

1. 定义

num = {}
print(type(num))
num2 = {1,2,3,4,5}
print(type(num2))
<class 'dict'>
<class 'set'>
集合的数据是唯一的
# 会自动去除重复数据
num2 = {1,2,3,4,5,5,3,2}
print(num2)
{1, 2, 3, 4, 5}
集合的数据是无序的
# 以下表达会报错
num2[2]

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

TypeError                                 Traceback (most recent call last)

<ipython-input-4-87e68eb3c3c4> in <module>()
----> 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)

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

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

转载于:https://www.cnblogs.com/nigream/p/11251126.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值