給集合set添加元素的兩種方法:add 與 update 的區別

1、add 方法:只能添加可哈希元素,不能添加字典、列表、集合等不可哈希元素。如果元素已存在,會被忽略。

x = {"apple", "orange", "pear"}

""" 添加 字符串 """
	x.add("A")
	x
# Out[70]: {'A', 'apple', 'orange', 'pear'}

""" 添加元組 """
x.add(('a', 'b'))
x
# Out[78]: {('a', 'b'), 'A', 'apple', 'orange', 'pear'}

""" 添加 列表 """
# x.add(['a', 'b'])  # 報錯:TypeError: unhashable type: 'list'

""" 添加 字典 """
# x.add({'a': 1, 'b': 2})  # TypeError: unhashable type: 'dict'

2、update 方法:可哈希 或 不可哈希 元素都能添加。如果元素已存在,會被忽略。他的工作原理是,將可迭代對象進行遍歷後的元素添加到集合中

x = {"apple", "orange", "pear"}

""" 添加 字符串 """
x.update("AB")
x	
# Out[70]: {'A', 'B', 'apple', 'orange', 'pear'}

""" 添加元組 """
x.update(('a', 'b'))
x
# Out[88]: {'A', 'B', 'a', 'apple', 'b', 'orange', 'pear'}

""" 添加 列表 """
x.update(['a', 'c'])  # 元素 "a" 不會被重複添加
x
# Out[93]: {'A', 'B', 'a', 'apple', 'b', 'c', 'orange', 'pear'}  

""" 添加 字典 """
x.update({'c': 1, "d": 2})  # 對於字典,只添加字典的鍵
x
# Out[96]: {'A', 'B', 'a', 'apple', 'b', 'c', 'd', 'orange', 'pear'}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章