集合中的update()函数将集合中的元素(作为参数传递)添加到集合中。
用法:
set1.update(set2)
Here set1 is the set in which set2 will be added.
参数:
Update()方法仅接受一个参数。单个参数可以是集合,列表,元组或字典。它会自动转换为集合并添加到集合中。
返回值:此方法将set2添加到set1且不返回任何内容。
代码1:
# Python program to demonstrate the
# use of update() method
list1 = [1, 2, 3]
list2 = [5, 6, 7]
list3 = [10, 11, 12]
# Lists converted to sets
set1 = set(list2)
set2 = set(list1)
# Update method
set1.update(set2)
# Print the updated set
print(set1)
# List is passed as an parameter which
# gets automatically converted to a set
set1.update(list3)
print(set1)
输出:
{1, 2, 3, 5, 6, 7} {1, 2, 3, 5, 6, 7, 10, 11, 12}
代码2:
# Python program to demonstrate the
# use of update() method
list1 = [1, 2, 3, 4]
list2 = [1, 4, 2, 3, 5]
alphabet_set = {'a', 'b', 'c'}
# lists converted to sets
set1 = set(list2)
set2 = set(list1)
# Update method
set1.update(set2)
# Print the updated set
print(set1)
set1.update(alphabet_set)
print(set1)
输出:
{1, 2, 3, 4, 5} {1, 2, 3, 4, 5, 'c', 'b', 'a'}
相关用法
注:本文由纯净天空筛选整理自Striver大神的英文原创作品 Python Set | update()。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。