【Python】Python - 新增Set items。Python Add Set Items.
【Python】Python - 新增Set items。Python Add Set Items.
新增 Items
一旦建立了set,則無法修改這個set的items,但可以新增。
可以使用add() 方法去新增items到set裡面。
範例
使用add() 方法去新增items到set裡面:
thisset = {"apple", "banana", "cherry"}
thisset.add("orange")
print(thisset)範例: {'orange', 'apple', 'cherry', 'banana'}從其他sets新增 Sets的items
從其他set的items新增到另一個set可以使用update() 方法。
範例
增加元素 從 tropical 與 thisset 到 newset:
thisset = {"apple", "banana", "cherry"}
tropical = {"pineapple", "mango", "papaya"}
thisset.update(tropical)
print(thisset)上面輸出: {'apple', 'mango', 'cherry', 'pineapple', 'banana', 'papaya'}新增任何的迭代
在update() 方法裡面的物件,不一定需要是set,可以是任何的可迭代物件,如tuples, lists, dictionaries...等。
範例
從list的元素增加代set裡面:
thisset = {"apple", "banana", "cherry"}
mylist = ["kiwi", "orange"]
thisset.update(mylist)
print(thisset)上面輸出: {'banana', 'cherry', 'apple', 'orange','kiwi'}
留言
張貼留言