Python set add (Python 集合添加)

Python 的 add 函数用于向现有集合添加一个元素。本节将讨论如何使用此函数,set add 方法的语法如下:

setName.add(element)

此 set add 函数仅接受一个参数值。但是,您可以将元组作为参数添加。请记住,您不能插入现有或重复的值。

Python set add 示例

此函数可帮助您将新元素添加到现有集合中。下面的代码将香蕉添加到现有的水果集合中并打印出来。

FruitSet = {'apple', 'Mango', 'orange', 'cherry','kiwi'}
print("\nOld Items = ", FruitSet)

FruitSet.add('banana')
print("New Items = ", FruitSet)
Old Items =  {'Mango', 'orange', 'cherry', 'kiwi', 'apple'}
New Items =  {'Mango', 'orange', 'cherry', 'kiwi', 'apple', 'banana'}

让我向您展示另一个 Python set add 函数的示例。这样,您就可以获得一个完整的概念。此示例将整数值 125 添加到现有的整数元素中。

IntSet = {10, 20, 30,40}
print("\nOld Items = ", IntSet)

IntSet.add(125)
print("New Items = ", IntSet)
Old Items =  {40, 10, 20, 30}
New Items =  {40, 10, 20, 125, 30}

提示:请参阅本编程语言中的集合文章,以了解有关它们的所有详细信息。

在此示例中,我们使用此方法将一个元素添加到现有元素中。

mySet = {1, 2, 4, 5}
print("Old Elements = ", mySet)

mySet.add(3)
print("New Elements = ", mySet)

FruitSet = {'apple', 'Mango', 'orange', 'cherry','kiwi'}
print("\nOld Elements = ", FruitSet)

FruitSet.add('banana')
print("New Elements = ", FruitSet)
Old Elements = {1, 2, 4, 5}
New Elements = {1, 2, 3, 4, 5}

Old Elements = {'kiwi', 'orange', 'Mango', 'cherry', 'apple'}
New Elements = {'kiwi', 'orange', 'banana', 'Mango', 'cherry', 'apple'}

如何将元组添加到 Python 集合中?

此示例显示了如何将元组添加到现有集合中。与任何其他元素一样,您可以使用此函数添加元组。

IntSet = {10, 20, 30,40}
print("\nOld Set Items = ", IntSet)

tupExample = (125, 225, 345)

IntSet.add(tupExample)
print("New Set Items = ", IntSet)
set add Function Example

重复元素示例

此示例与上面相同,它将元组元素添加到集合中。但是,我们将同一元组添加了多次。正如我们所提到的,元组不接受重复项,此程序仅添加一次元组。

IntSet = {10, 20, 30,40}
print("\nOld = ", IntSet)

tupExample = (125, 225, 345)

IntSet.add(tupExample)
print("New = ", IntSet)

IntSet.add(tupExample)
print("Repeated = ", IntSet)
Old =  {40, 10, 20, 30}
New =  {40, 10, (125, 225, 345), 20, 30}
Repeated =  {40, 10, (125, 225, 345), 20, 30}

在此示例中,我们尝试使用此方法将列表添加到现有集合中。

IntSet = {10, 25, 30, 40, 50}
print("\nOld Items = ", IntSet)

ListExample = ['apple', 'Orange', 'Grape', 'Mango'] 

IntSet.add(ListExample)
print("New Items = ", IntSet)

从输出中可以看到,它正在抛出错误,因为列表是可变的。还有其他插入元素的方法。我们稍后会解释。


Old Items =  {50, 40, 25, 10, 30}
Traceback (most recent call last):
  File "/Users/suresh/Desktop/simple.py", line 7, in <module>
    IntSet.add(ListExample)
TypeError: unhashable type: 'list'
>>>