Python学习-集合的常见用法

本文详细介绍了如何使用Python中的集合进行各种操作,包括并集、交集、差集、对称差集等,并演示了如何通过集合来去重列表。此外还讲解了集合的子集、父集判断以及元素的添加、移除等操作。

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

st = [1,2,3,4,5]
ct = [2,3,4,5,76]
list = set(["name", 'list', 'try'])
list2 = set(["name", 'list', 'try', 'but', 'test'])
# 两个列表去重,利用集合

st = set(st)   #设为集合
ct = set(ct)
print(st, type(st))

sct0 = st.union(ct)  #并集
sct = st | ct   #并集

sct2 = st.intersection(ct) #交集
sct1 = st & ct  #交集

sct3 = st.difference(ct) #差集
sct4 = st - ct   #差集,st中减去ct中的元素


print(sct0)
print(sct)
print(sct1)
print(sct2)

print(sct3)
print(sct4)

print(list.intersection(list2))

#子集
sct_0 = set([2, 3])
print(sct_0.issubset(st))  #判断前者是否为后者的子集
print(sct_0.issuperset(st))#判断前者是否为后者的父集


#对称差集
print(st.symmetric_difference(ct))  # 去掉两者的并集
print(st.copy())

cp_st = st.copy()
print(cp_st)

#添加单个元素
cp_st.add(11)
print(cp_st)
print('%s st list is here' % st) #会发现st中没有变
#添加多个元素,位置是随机的
cp_st.update([11, 22, 'key'])
print(cp_st)

#判断是否交集是空
print(cp_st.isdisjoint(list2))

#去除一个元素
cp_st.remove(11)
print(cp_st)

cp_st.add("str")
print(cp_st)
cp_st.remove('str')
print(cp_st)

cp_st.pop()   #这个算是随机删除
print(cp_st)

cp_st.discard('key')  #指定删除哪一个,最好是数字,但是不是数字也能用。会有提示
print(cp_st)

 

转载于:https://www.cnblogs.com/Ian-learning/p/7827852.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值