📅  最后修改于: 2020-10-30 06:01:59             🧑  作者: Mango
Python add()方法将新元素添加到集合中。它需要一个参数,即要添加的元素。它向呼叫者返回无。方法签名如下。
add(elem)
elem:要添加的元素。
它返回None。
让我们来看一些add()方法的示例,以了解其功能。
一个在集合中添加新元素的简单示例。它返回一个修改后的集合。
# Python set add() Method
# Creating a set
set = {1,2,3}
# Displaying elements
print(set)
# Calling method
set.add(4) # Adding new element
# Displaying elements
print("After adding new element: \n",set)
输出:
{1, 2, 3}
After adding new element:
{1, 2, 3, 4}
添加已经存在的元素不会修改集合。 Set不存储重复的元素。请参见下面的示例。
# Python set add() Method
# Creating a set
set = {1,2,3}
# Displaying elements
print(set)
# Calling method
set.add(2) # Adding duplicate element
# Displaying elements
print("After adding new element: \n",set)
输出:
{1, 2, 3}
After adding new element:
{1, 2, 3}
Set还允许存储其他数据结构,例如元组,列表等。请参见下面的示例。
# Python set add() Method
# Creating a set
set = {1,2,3}
# Displaying elements
print(set)
tup = (4,5) # Creating tuple
# Calling method
set.add(tup) # Adding tuple to the set
# Displaying elements
print("After adding new element: \n",set)
dup = (2,3,4)
set.add(dup) # Adding duplicate using tuple
print("After adding tuple: \n",set)
输出:
{1, 2, 3}
After adding new element:
{(4, 5), 1, 2, 3}
After adding tuple:
{1, 2, 3, (4, 5), (2, 3, 4)}