如果集合中不存在給定元素,則該集合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。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。