举报投诉联系我们 手机版 热门标签 VUE中文网
您的位置:VUE中文网 > python 集合remove Python3 集合 remove() 方法

python 集合remove Python3 集合 remove() 方法

2023-03-14 00:17 Python3教程

python 集合remove Python3 集合 remove() 方法

python 集合remove

Python集合remove()方法用于移除集合中指定的元素。如果元素不存在,则会引发KeyError。

# 定义一个集合
s = {1, 2, 3, 4}
 
# 移除元素 2
s.remove(2)
 
print(s) # 输出 {1, 3, 4}

remove() 方法接受一个要删除的元素作为参数,如果该元素不存在,则会引发 KeyError 错误。因此,在使用 remove() 方法之前,最好使用 in 运算符来检查一下该元素是否存在于集合中。

 
# 定义一个集合 
s = {1, 2, 3, 4} 
  # 检查 5 是否存在于集合中 
if 5 in s:   # 如果 5 存在于集合中   s.remove(5)   # 移除 5   else:   print("5 不存在于集合中") 

remove() 方法不会返回任何值,它只是从集合中删除一个元素。如果要获得被删除的元素的值,可以使用 discard() 方法。discard() 方法也是用来删除集合中的元素,但它会返回被删除的值。

Python3 集合 remove() 方法

Python3 列表 Python 集合

描述

remove() 方法用于移除集合中的指定元素。

该方法不同于 discard() 方法,因为 remove() 方法在移除一个不存在的元素时会发生错误,而 discard() 方法不会。

语法

remove() 方法语法:

set.remove(item)

参数

  • item -- 要移除的元素

返回值

没有返回值。

实例

移除元素 banana:

实例 1

fruits = {"apple", "banana", "cherry"}
 
fruits.remove("banana") 
 
print(fruits)

输出结果为:

{"cherry", "apple"}

Python3 列表 Python 集合


阅读全文
以上是VUE中文网为你收集整理的python 集合remove Python3 集合 remove() 方法全部内容。
声明:本站所有文章资源内容,如无特殊说明或标注,均为采集网络资源。如若本站内容侵犯了原著者的合法权益,可联系本站删除。
相关文章
© 2024 VUE中文网 vue88.com 版权所有 联系我们