【Python基础系列】Part4.集合

四、集合
1.集合

集合是无序和无索引的集合。在集合中,不会有重复的元素。在 Python 中,集合用花括号编写。

创建集合

thisset = {"apple", "banana", "cherry"}
print(thisset)#{'banana', 'cherry', 'apple'}

访问集合

#您无法通过引用索引来访问 set 中的项目,因为 set 是无序的,项目没有索引。但是您可以使用 for 循环遍历 set 项目,或者使用 in 关键字查询集合中是否存在指定值。
thisset = {"apple", "banana", "cherry"}
for i in thisset:
    print(i)
#apple
#banana
#cherry

检查是否存在某个元素

thisset = {"apple", "banana", "cherry"}

print("banana" in thisset)#True

添加单个元素

#add()方法
thisset = {"apple", "banana", "cherry"}
thisset.add("orange")
print(thisset)

添加多个元素

thisset = {"apple", "banana", "cherry"}
thisset.update(["orange", "mango", "grapes"])
print(thisset)

集合的长度

#len()方法
thisset = {"apple", "banana", "cherry"}
print(len(thisset))#3

删除集合中的元素

#要删除集合中的项目,请使用 remove() 或 discard() 方法。
#如果要删除的项目不存在,则 remove() 将引发错误。
#如果要删除的项目不存在,则 discard() 不会引发错误。
#还可以使用 pop() 方法删除项目,但此方法将删除随机的一项
thisset = {"apple", "banana", "cherry"}
thisset.remove("banana")
print(thisset)

thisset = {"apple", "banana", "cherry"}
thisset.discard("banana")
print(thisset)

thisset = {"apple", "banana", "cherry"}
x = thisset.pop()
print(x)
print(thisset)

清空集合

#clear()方法
thisset = {"apple", "banana", "cherry"}
thisset.clear()
print(thisset)

彻底删除集合

#del 方法
thisset = {"apple", "banana", "cherry"}
del thisset
print(thisset)

合并两个集合

#可以使用 union() 方法返回包含两个集合中所有项目的新集合,也可以使用 update() 方法将一个集合中的所有项目插入另一个集合中
set1 = {"a", "b" , "c"}
set2 = {1, 2, 3}
set3 = set1.union(set2)
print(set3)

set1 = {"a", "b" , "c"}
set2 = {1, 2, 3}
set1.update(set2)
print(set1)

构造集合

#set() 构造函数来创建集合
thisset = set(("apple", "banana", "cherry")) # 请留意这个双括号
print(thisset)
2.总结

学到了:

  • 集合定义
  • 访问集合
  • 各种操作集合的方法
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值