可變集合類型的方法:
演示實例:
一、集合類型方法
>>> s = set('cheeseshop') >>> t = set('bookshop') >>> s set(['c', 'e', 'h', 'o', 'p', 's']) >>> t set(['b', 'h', 'k', 'o', 'p', 's']) >>> s.issubset(t) False >>> s.issuperset(t) False >>> s.union(t) set(['c', 'b', 'e', 'h', 'k', 'o', 'p', 's']) >>> s.intersection(t) set(['h', 's', 'o', 'p']) >>> s.difference(t) set(['c', 'e']) >>> s.symmetric_difference(t) set(['b', 'e', 'k', 'c']) >>> s.copy() set(['p', 'c', 'e', 'h', 's', 'o'])
二、可變集合類型的方法
1、s.update(t)——用t中的元素修改s,即s現在包含s或t的成員。
>>> s.update(t) >>> s set(['c', 'b', 'e', 'h', 'k', 'o', 'p', 's'])
2、s.intersection_update(t)——s中的成員是共同屬于s和t中的元素。
>>> s = set('cheeseshop') >>> t = set('bookshop') >>> s.intersection_update(t) >>> s set(['h', 's', 'o', 'p'])
3、s.difference_update(t)——s中的成員是屬于s但不包含在t中的元素。
>>> s = set('cheeseshop') >>> t = set('bookshop') >>> s.difference_update(t) >>> s set(['c', 'e'])
4、s.symmetric_difference_update(t)——s中的成員更新為那些包含在s或t中,但不是s和t共有的元素。
>>> s = set('cheeseshop') >>> t = set('bookshop') >>> s.symmetric_difference_update(t) >>> s set(['c', 'b', 'e', 'k'])
5、s.add(obj)——在集合s中添加對象obj。
>>> s.add('o') >>> s set(['c', 'b', 'e', 'k', 'o'])
6、s.remove(obj)——從集合s中刪除對象obj,如果obj不是集合s中的元素(obj not in s),將引發KeyError。
>>> s.remove('b') >>> s set(['c', 'e', 'k', 'o']) >>> s.remove('a')
Traceback (most recent call last): File "
", line 1, in s.remove('a') KeyError: 'a'
7、s.discard(obj)——如果obj是集合s中的元素,從集合s中刪除對象obj。
>>> s.discard('a') >>> s set(['c', 'e', 'k', 'o']) >>> s.discard('e') >>> s set(['c', 'k', 'o'])
8、s.pop()——刪除集合是中的任意一個對象,并返回它。
>>> s.pop() 'c' >>> s set(['k', 'o'])
9、s.clear()——刪除集合s中的所有元素。
>>> s.clear() >>> s set([])
聲明:本網頁內容旨在傳播知識,若有侵權等問題請及時與本網聯系,我們將在第一時間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com