Python remove()

python 中的remove()函数有助于从集合中移除指定的元素。如果在集合中找不到给定的元素,该方法将引发键错误。

 **set.remove(element)** #where element which is to be remove 

移除()参数:

remove()函数接受一个参数。这个方法类似于discard(),不同的是discard()方法不会引发错误,即使找不到元素并且集合保持不变。

参数 描述 必需/可选
元素 要从集合中移除的元素。 需要

移除()返回值

这个方法不返回值。它只是通过移除特定元素来更新集合。如果在集合中找不到给定的元素,此方法将引发键错误。

Python 中remove()方法的示例

示例 1:如何从集合中移除元素?

 # flowers set
flowers = {'Dalia', 'Rose', 'Lotus', 'Sunflower'}

# 'Lotus' is removed
flowers.remove('Lotus')

# Updated flowers set
print('Updated flowers Set: ', flowers) 

输出:

 Updated flowers Set:{'Dalia', 'Rose', 'Sunflower'} 

示例 2:尝试移除不在集合中的元素

 # flowers set
flowers = {'Dalia', 'Rose', 'Lotus', 'Sunflower'}

# 'Lotus' is removed
flowers.remove('cat')

# Updated flowers set
print('Updated flowers Set: ', flowers) 

输出:

 Traceback (most recent call last):
  File "<stdin>", line 5, in <module>flowers.remove('cat')
KeyError: 'cat'</module></stdin> 

本文链接:https://my.lmcjl.com/post/6716.html

展开阅读全文

4 评论

留下您的评论.