Python第四天笔记——集合

这篇笔记介绍了Python中的集合特性,如无序、不可重复且不可更改。重点讲述了集合的创建、基本操作,包括增(add、update)、删(pop、discard、remove)、查,以及集合的交集(&)、并集(|)和差集(-)运算。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

集合

特点:

  • 无序
  • 不可重复
  • 不可更改
    • 内部的元素是可哈希的
    • 集合本身是不可哈希的
  • 用{}括起来的单元素数据集,不支持索引

用途:

  • 去重(列表----->集合,自动去重)
  • 关系测试

集合的创建

#空集合的创建

st=set()
print(st)

st={}
print(type(st))

#输出结果:
set() <class 'set'>
{} <class 'dict'>

#多元素集合的创建

st={1,2,3,'hh'}
print(type(st))

#输出结果:
<class 'set'>

#强转

1、列表强转
li=[23,34,'aa','bb']
st=set(li)
print(st,type(st))

#输出结果:
{34, 'bb', 'aa', 23} <class 'set'>  #无序的

2、字符串强转
sr="python"
st=set(sr)
print(st,type(st))

#输出结果:
{'n', 'o', 'p', 'y', 'h', 't'} <class 'set'>

3、字典强转
dict={'id': 20190201, 'age': 18, 'name': 'cl'}
st=set(dict)
print(st,type(st))

#输出结果:
{'id', 'age', 'name'} <class 'set'>

集合的基本操作

(1)增

  • set.add()
  • set.update()
st.add(4)
print(st)

st.update('5')
print(st)

#输出结果:
(add):
{1, 2, 3, 'a', 'hh', '4'}
(update):
{1, 2, 3, 'a', '5', 'hh', '4'}

(2)删

  • set.pop():删除排序最小的一个元素
  • set.discard()
  • set.remove()
  • del set
1、
st.pop()
print(st)

#输出结果:
{2, 3, '5', 'a', 'hh', '4'}

2、
st.discard('a')
print(st)

#输出结果:
{2, 3, '5', 'hh', '4'}

3、
st.remove('5')
print(st)

#输出结果:
{2, 3, 'hh', '4'}

(3)改

​ #不可改

(4)查

​ #不可查

遍历

st={1,2,3,'hh','a'}
for i in st:
    print(i,end=' ')

for i in enumerate(st):
    print(i, end=' ')
    
#输出结果:    
1 2 3 hh a 
(0, 1) (1, 2) (2, 3) (3, 'hh') (4, 'a') 

集合的基本运算

a=set("abc")
b=set("cde")
c=set("ab")
print(a,b,c)
print(c<a)
print(b>a)
print(c.issubset(a))

#输出结果: 
{'c', 'a', 'b'} {'e', 'c', 'd'} {'a', 'b'}
True
False
True

交集

  • &
  • set.intersection()
a=set("abc")
c=set("ab")
print(a & c)
print(a.intersection(c))

#输出结果: 
{'a', 'b'}

并集

  • |
  • set.union()
a=set("abcd")
b=set("cdef")
print(a|b)
print(a.union(b))

#输出结果: 
{'e', 'a', 'c', 'b', 'd', 'f'}

差集

  • -
  • set.difference()
a=set("abcd")
b=set("cdef")
print(b-a)
print(b.difference(a))

#输出结果: 
{'f', 'e'}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值