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