Python 中的 update() 函数通过添加来自另一个集合(即给定可迭代对象)的元素来帮助更新集合。如果两个集合中都存在相同的元素,则只保留一个实例。
A.update(iterable) #where iterable such as list, set, dictionary, string, etc.
update() 函数接受一个可迭代参数。如果给定的可迭代对象是列表、元组或字典,该函数会自动将其转换为集合并将元素添加到集合中。
| 参数 | 描述 | 必需/可选 |
|---|---|---|
| 可迭代对象 | 将可迭代对象插入当前集合 | 必需 |
update() 函数不返回任何值,它只是通过向现有集合添加元素来更新它。此函数可以接受多个由逗号分隔的可迭代参数。
X = {'x', 'y'}
Y = {5, 4, 6}
result = X.update(Y)
print('X =', X)
print('result =', result)
输出
A = {'x', 5, 4, 6, 'y'}
result = None
alphabet_str = 'abc'
num_set = {1, 2}
# add elements of the string to the set
num_set.update(alphabet_str)
print('Numbers Set =', num_set)
dict_info= {'key': 1, 'lock' : 2}
num_set = {'a', 'b'}
# add keys of dictionary to the set
num_set.update(dict_info)
print('Numbers Set=', num_set)
输出
Numbers Set = {'c', 1, 2, 'b', 'a'}
Numbers Set = {'key', 'b', 'lock', 'a'}