当前位置: 首页>>代码示例>>用法及示例精选>>正文


Python set add()用法及代码示例

如果集合中不存在给定元素,则该集合add()方法会将其添加到集合中。

用法:

set.add(elem)
The add() method doesn't add an element to the
set if it's already present in it otherwise it 
will get added to the set.
参数:
add() takes single parameter(elem) which needs to 
be added in the set.
返回:
The add() method doesn't return any value.
# set of letters 
GEEK = {'g', 'e', 'k'} 
  
# adding 's' 
GEEK.add('s') 
print('Letters are:', GEEK) 
  
# adding 's' again 
GEEK.add('s') 
print('Letters are:', GEEK)

输出:


('Letters are:', set(['k', 'e', 's', 'g']))
('Letters are:', set(['k', 'e', 's', 'g'])

应用:

It is used to add a new element to the set. 
# set of letters 
GEEK = {6, 0, 4} 
  
# adding 1 
GEEK.add(1) 
print('Letters are:', GEEK) 
  
# adding 0  
GEEK.add(0) 
print('Letters are:', GEEK)

输出:

('Letters are:', set([0, 1, 4, 6]))
('Letters are:', set([0, 1, 4, 6]))


将元组添加到集合中:

# Python code to demonstrate addition of tuple to a set. 
s = {'g', 'e', 'e', 'k', 's'} 
t = ('f', 'o') 
  
# adding tuple t to set s. 
s.add(t) 
  
print(s)

输出:

{'k', 's', 'e', 'g', ('f', 'o')}


相关用法

注:本文由纯净天空筛选整理自pawan_asipu大神的英文原创作品 set add() in python。非经特殊声明,原始代码版权归原作者所有,本译文的传播和使用请遵循“署名-相同方式共享 4.0 国际 (CC BY-SA 4.0)”协议。