Python 集合(Sets)2

发布时间 2023-10-12 21:31:34作者: 小万哥丶

访问项

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

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

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

for x in thisset:
  print(x)

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

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

print("banana" in thisset)

Python - 添加集合项

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

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

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

thisset.add("orange")

print(thisset)

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

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

thisset = {"apple", "banana", "cherry"}
tropical = {"pineapple", "mango", "papaya"}

thisset.update(tropical)

print(thisset)

添加任何可迭代对象

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

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

thisset = {"apple", "banana", "cherry"}
mylist = ["kiwi", "orange"]

thisset.update(mylist)

print(thisset)

Python - 删除集合项

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

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

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

thisset.remove("banana")

print(thisset)

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

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

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

thisset.discard("banana")

print(thisset)

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

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

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

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

x = thisset.pop()

print(x)

print(thisset)

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

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

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

thisset.clear()

print(thisset)

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

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

del thisset

print(thisset)

Python - 遍历集合

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

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

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

for x in thisset:
  print(x)

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

最后

为了方便其他设备和平台的小伙伴观看往期文章,链接奉上:

公众号搜索Let us Coding知乎开源中国CSDN思否掘金InfoQ简书博客园慕课51CTOhelloworld腾讯开发者社区阿里开发者社区

看完如果觉得有帮助,欢迎点赞、收藏关注