python集合set update()方法,添加iterable中“元素”
集合update()方法
python的集合除了可以用add()方法添加元素之外,也可以用update()方法来添加元素或集合(或其它pythoniterable对象)到调用对象之中(这是update()方法与add()不同的地方之一),如果被添加的元素在调用对象之中已经存在,集合的去重功能只会保留一个。
集合update()语法及参数
set.update( iterable )
参数解析表:
参数 | 描述 |
---|---|
iterable | python可迭代对象,如集合set、列表list、元组tuple、字符串str、range类型等等 |
集合update()返回值
无。
集合update()方法实例代码
>>> set1 = {1,2}
>>> set1.update() #不传递参数
>>> set1
{1, 2}
>>> set1.update({3,4,5}) #参数为集合set
>>> set1
{1, 2, 3, 4, 5}
>>> set1.update([6,7]) #参数为列表list
>>> set1
{1, 2, 3, 4, 5, 6, 7}
>>> set1.update((8,9)) #参数为元组tuple
>>> set1
{1, 2, 3, 4, 5, 6, 7, 8, 9}
>>> set1.update('10') #参数为字符串str
>>> set1
{1, 2, 3, 4, 5, 6, 7, 8, 9, '0', '1'}
>>> set1.update({'a':10,'b':11}) #参数为字典dict
>>> set1
{1, 2, 3, 4, 5, 6, 7, 8, 9, '0', 'a', '1', 'b'}
>>> set1.update(range(3,12)) #参数为range类型
>>> set1
{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, '0', 11, 'a', '1', 'b'}