前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Python 集合(Sets)2

Python 集合(Sets)2

原创
作者头像
小万哥
发布2023-10-12 21:30:27
1130
发布2023-10-12 21:30:27
举报
文章被收录于专栏:程序人生丶程序人生丶

访问项

您无法通过引用索引或键来访问集合中的项。但是,您可以使用for循环遍历集合项,或者使用in关键字检查集合中是否存在指定的值。

示例,遍历集合并打印值:

代码语言:Python
复制
thisset = {"apple", "banana", "cherry"}

for x in thisset:
  print(x)

示例,检查集合中是否存在 "banana":

代码语言:Python
复制
thisset = {"apple", "banana", "cherry"}

print("banana" in thisset)

Python - 添加集合项

一旦创建了集合,您就不能更改其项,但可以添加新项。要向集合添加一个项,请使用add()方法。

示例,使用add()方法向集合添加一个项:

代码语言:Python
复制
thisset = {"apple", "banana", "cherry"}

thisset.add("orange")

print(thisset)

要将另一个集合中的项添加到当前集合中,请使用update()方法。

示例,将tropical中的元素添加到thisset中:

代码语言:Python
复制
thisset = {"apple", "banana", "cherry"}
tropical = {"pineapple", "mango", "papaya"}

thisset.update(tropical)

print(thisset)

添加任何可迭代对象

update()方法中的对象不必是集合,可以是任何可迭代对象(元组、列表、字典等)。

示例,将列表的元素添加到集合中:

代码语言:Python
复制
thisset = {"apple", "banana", "cherry"}
mylist = ["kiwi", "orange"]

thisset.update(mylist)

print(thisset)

Python - 删除集合项

要删除集合中的项,可以使用remove()discard()方法。

示例,使用remove()方法删除 "banana":

代码语言:Python
复制
thisset = {"apple", "banana", "cherry"}

thisset.remove("banana")

print(thisset)

注意:如果要删除的项不存在,remove()将引发错误。

示例,使用discard()方法删除 "banana":

代码语言:Python
复制
thisset = {"apple", "banana", "cherry"}

thisset.discard("banana")

print(thisset)

注意:如果要删除的项不存在,discard()不会引发错误。

您还可以使用pop()方法来删除一个项,但此方法将删除一个随机项,因此不能确定删除哪个项。pop()方法的返回值是已删除的项。

示例,使用pop()方法删除一个随机项:

代码语言:Python
复制
thisset = {"apple", "banana", "cherry"}

x = thisset.pop()

print(x)

print(thisset)

注意:由于集合是无序的,因此在使用pop()方法时无法确定删除哪个项。

示例,clear()方法将清空集合:

代码语言:Python
复制
thisset = {"apple", "banana", "cherry"}

thisset.clear()

print(thisset)

示例,del关键字将完全删除集合:

代码语言:Python
复制
thisset = {"apple", "banana", "cherry"}

del thisset

print(thisset)

Python - 遍历集合

您可以使用for循环遍历集合项:

示例,遍历集合并打印值:

代码语言:Python
复制
thisset = {"apple", "banana", "cherry"}

for x in thisset:
  print(x)

希望这些信息对您有所帮助!如果有任何问题或需要更多解释,请随时提问。

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 访问项
  • Python - 添加集合项
  • 添加任何可迭代对象
  • Python - 删除集合项
  • Python - 遍历集合
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档