首页 > 编程知识 正文

Python update()

时间:2023-11-24 15:27:51 阅读:308722 作者:ULOK

python 中的update()函数通过添加来自另一个集合(即来自给定 iterable)的元素来帮助更新该集合。如果两个集合中存在相同的元素,则只放置一个实例。

 **A.update(iterable)** #where iterable such as list, set, dictionary, string, etc. 

更新()参数:

update()函数接受一个可迭代的参数。如果给定的表是一个列表、元组或字典,这个函数会自动将其转换成一个集合,并将元素添加到该集合中。

参数 描述 必需/可选
可重复的 当前集合中的可迭代插入 需要

更新()返回值

update()函数不返回值,它只是通过向现有集合中添加元素来更新它。该函数可以接受多个用逗号分隔的可重复参数。

Python 中update()方法的示例

示例 Python set 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 

示例 2:如何使用update()向 Set 添加字符串和字典元素?

 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'} 

版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。