集合中的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()。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。