測試環境為 CentOS 8 x86_64 (虛擬機)
參考文章 – https://docs.python.org/zh-tw/3/tutorial/datastructures.html#sets
集合 (Sets) 存儲一組無序且不重複的元素,支援 and 聯集 , or 交集 , not 差集和 xor 互斥等數學運算.
其他資料型態
- String – https://benjr.tw/104605
使用單,雙 或是 三重引號來表示為字串. - List – https://benjr.tw/104232
使用 中括弧 [ ] 表示 ,其中資料用逗號做區隔. - dic – https://benjr.tw/104234
使用 大括弧 { } 表示 ,格式為 key:valu ( pair 組成 並由逗點隔開). - Tuple – https://benjr.tw/104461
使用 小括號 ( ) 表示 ,其中資料用逗號做區隔. - set – https://benjr.tw/104696
大括弧 { } 表示 ,其中資料用逗號做區隔.
[root@localhost ~]# python3 Python 3.6.8 (default, Mar 25 2022, 11:15:52) [GCC 8.5.0 20210514 (Red Hat 8.5.0-10)] on linux Type "help", "copyright", "credits" or "license" for more information.
- 範例 : 集合 (Sets)無序且不重複的元素
>>> s1={1,1,2,3,4} >>> s1 {1, 2, 3, 4}
- 範例 : and 聯集 , or 交集 , not 差集和 xor 互斥等數學運算.
>>> s1={1,2,3,4} >>> s1 {1, 2, 3, 4} >>> s2={4,5,6,7} >>> s2 {4, 5, 6, 7}
not 差集
>>> s1-s2 {1, 2, 3}
and 聯集
>>> s1&s2 {4}
or 交集
>>> s1|s2 {1, 2, 3, 4, 5, 6, 7}
s1 與 s2
xor 互斥 (xor 為相同為 0 ,不同為 1 , 只會顯示 1 (不同的))
>>> s1^s2 {1, 2, 3, 5, 6, 7}
- 範例 : 使用 set 建立 Set 資料型態物件
需使用 小括弧 () .>>> a = set('abracadabra') >>> a {'b', 'd', 'a', 'r', 'c'}
- 範例 : set comprehensions (集合綜合運算)
>>> a = {x for x in 'abracadabra' if x not in 'abc'} >>> a {'d', 'r'}
set 的 Method – https://www.w3schools.com/python/python_ref_set.asp
- add()
Adds an element to the set - clear()
Removes all the elements from the set - copy()
Returns a copy of the set - difference()
Returns a set containing the difference between two or more sets - difference_update()
Removes the items in this set that are also included in another, specified set - discard()
Remove the specified item - intersection()
Returns a set, that is the intersection of two or more sets - intersection_update()
Removes the items in this set that are not present in other, specified set(s) - isdisjoint()
Returns whether two sets have a intersection or not - issubset()
Returns whether another set contains this set or not - issuperset()
Returns whether this set contains another set or not - pop()
Removes an element from the set - remove()
Removes the specified element - symmetric_difference()
Returns a set with the symmetric differences of two sets - symmetric_difference_update()
inserts the symmetric differences from this set and another - union()
Return a set containing the union of sets - update()
Update the set with another set, or any other iterable
沒有解決問題,試試搜尋本站其他內容