python 示例_带有示例的Python Set remove()方法

python 示例

设置remove()方法 (Set remove() Method)

remove() method is used to remove a specified element from the set, the method accepts an element and removes from the set if it exists, if the element does not exist in the set, the method returns an error.

remove()方法用于从集合中删除指定的元素,该方法接受一个元素并从集合中删除(如果存在),如果该元素在集合中不存在,则该方法返回错误。

Syntax:

句法:

    set_name.remove(element)

Parameter(s):

参数:

  • element – It represents the element to be removed from the list.

    element –它表示要从列表中删除的元素。

Return value:

返回值:

The return type of this method is <class 'NoneType'>, it returns nothing.

此方法的返回类型为<class'NoneType'> ,它什么也不返回。

Example 1:

范例1:

# Python Set remove() Method with Example

# declaring the sets
cars = {"Porsche", "Audi", "Lexus", "Mazda", "Lincoln"}
nums = {100, 200, 300, 400, 500}

# printing the sets before removing
print("Before the calling remove() method...")
print("cars: ", cars)
print("nums: ", nums)

# Removing the elements from the sets
cars.remove("Porsche")
cars.remove("Mazda")

nums.remove(100)
nums.remove(500)

# printing the sets after removing
print("After the calling remove() method...")
print("cars: ", cars)
print("nums: ", nums)

Output

输出量

Before the calling remove() method...
cars:  {'Mazda', 'Audi', 'Porsche', 'Lexus', 'Lincoln'}
nums:  {100, 200, 300, 400, 500}
After the calling remove() method...
cars:  {'Audi', 'Lexus', 'Lincoln'}
nums:  {200, 300, 400}

Demonstrating example, how method raises error if element is not find in the set?

演示示例,如果在集合中找不到元素,方法将如何引发错误?

Example 2:

范例2:

# Python Set remove() Method with Example

# declaring the sets
cars = {"Porsche", "Audi", "Lexus", "Mazda", "Lincoln"}

# printing the set
print("cars: ", cars)
# removing an item (which exists in the set)
cars.remove("Porsche")
# printing the set again
print("cars: ", cars)

# removing an item (which does not exist in the set)
# it will return an error
cars.remove("BMW")

Output

输出量

cars:  {'Mazda', 'Audi', 'Lexus', 'Porsche', 'Lincoln'}
cars:  {'Mazda', 'Audi', 'Lexus', 'Lincoln'}
Traceback (most recent call last):
  File "main.py", line 15, in <module>
    cars.remove("BMW")
KeyError: 'BMW'


翻译自: https://www.includehelp.com/python/set-remove-method-with-example.aspx

python 示例

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值