注釋很詳細
collection={1,2,"apple","orange","cat"} # 查看一個數是否在集合中 in print("Tom 是否在集合中:","Tome" in collection) print("apple 是否在集合中:","apple" in collection) # 集合初始化時用set() pets={}是代表初始化了一個字典集 pets=set() # 集合添加元素用add()方法,刪除元素用discard() pets.add("dog") pets.add("cat") pets.add("bird") pets.add("zebra") print(pets) pets.discard("zebra") print(pets) # 集合的 與 或 非 print("並集:",pets | collection ) print("交集:",pets & collection) print("異或:",pets - collection) # 將一個字典集的keys轉為集合,用set(字典集名) dict1={"cat":1,"dog":2,"bird":3} print(set(dict1)) # 向一個集合中添加另一個集合用update()方法 collection.update([12,13,14]) print(collection)
for i in set("apple"): print(i,end=",") print() for j in "apple": print(j,end=",")
輸出結果”
E:\Program_Files\PythonAll\workspace\MyLearnProject\venv\Scripts\python.exe E:/Program_Files/PythonAll/workspace/MyLearnProject/pythonCode/collection/collectionFunc.py Tom 是否在集合中: False apple 是否在集合中: True {'dog', 'cat', 'bird', 'zebra'} {'dog', 'cat', 'bird'} 並集: {1, 2, 'bird', 'apple', 'orange', 'dog', 'cat'} 交集: {'cat'} 異或: {'dog', 'bird'} {'dog', 'cat', 'bird'} {1, 2, 12, 13, 14, 'apple', 'cat', 'orange'} l,p,e,a, a,p,p,l,e, Process finished with exit code 0