Python Set – 本篇會介紹Set的6種基本應用方法 – Set初始化, Set加入值, Set加入多個值, Set刪除值, Set清除所有值, Set for迴圈
注意事項:
- Set是沒有次序的, 不能用索引或Key去讀它
- Set內的值不能重覆
- Set內的值不能改變
Let’s go
方法 | 例子: |
初始化 Set Init | lst = {‘John’, ‘Peter’, ‘Mary’, ‘Marks’} print(lst) # {‘John’, ‘Peter’, ‘Mary’, ‘Marks’} |
加入值 Set Add 1 | lst = {‘John’, ‘Peter’, ‘Mary’, ‘Marks’} lst.add(“Tim”); print(lst) # {‘John’, ‘Peter’, ‘Mary’, ‘Marks’, ‘Tim’} |
加入多個值1 Set Add 2 | lst1 = {‘John’, ‘Peter’, ‘Mary’, ‘Marks’} lst2 = {‘Greenlands’, ‘Kingston’} lst1.update(lst2) print(lst1); # {‘Mary’, ‘John’, ‘Greenlands’, ‘Kingston’, ‘Peter’, ‘Marks’} |
加入多個值2 Set Add 3 | lst1 = {‘John’, ‘Peter’, ‘Mary’, ‘Marks’} lst2 = [‘Greenlands’, ‘Kingston’] lst1.update(lst2) print(lst1); # {‘Kingston’, ‘Greenlands’, ‘Mary’, ‘John’, ‘Peter’, ‘Marks’} |
刪除值1 Set Remove 1 | lst1 = {‘John’, ‘Peter’, ‘Mary’, ‘Marks’} lst2 = ‘Peter’ lst1.remove(lst2); print(lst1); # {‘John’, ‘Marks’, ‘Mary’} |
刪除值2 Set Remove 2 | lst1 = {‘John’, ‘Peter’, ‘Mary’, ‘Marks’} lst2 = ‘Peter’ lst1.discard(lst2); print(lst1); # {‘John’, ‘Marks’, ‘Mary’} |
刪除值3 Set Remove 3 | lst1 = {‘John’, ‘Peter’, ‘Mary’, ‘Marks’} lst2 = ‘Peter’ lst1.pop(); print(lst1); # {‘John’, ‘Marks’, ‘Mary’} |
刪除所有值 Set Remove 4 | lst1 = {‘John’, ‘Peter’, ‘Mary’, ‘Marks’}; del lst1 print(lst1); # name ‘lst1’ is not defined |
清除所有值 Set Clear | lst1 = {‘John’, ‘Peter’, ‘Mary’, ‘Marks’}; lst1.clear() print(lst1); # {} |
for迴圈 Set for | lst1 = {‘John’, ‘Peter’, ‘Mary’, ‘Marks’}; for x in lst1: print(x) # Peter # Marks # John # Mary |
(等如) | |
lst1 = {‘John’, ‘Peter’, ‘Mary’, ‘Marks’}; [print(x) for x in lst1] # Peter # Marks # John # Mary |
相關頁面
Python List – 學會List的9種基本應用方法 – 初始化, 加入值, 插入值, 追加值, 更新值, 刪除值, 清除所有值, 切片,排序, for迴圈
Python Tuple – 學會Tuple的3種基本應用方法 – 初始化,切片, for迴圈
Python Dictionary – 學會Dictionary的5種基本應用方法 – 初始化, 加入值, 更新值, 刪除值, foreach迴圈
參考資料: https://docs.python.org/3/tutorial/datastructures.html#sets