2016.07.17-18 集合方法
生活随笔
收集整理的這篇文章主要介紹了
2016.07.17-18 集合方法
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
集合(set):特性:1.集合的元素都是唯一的。2.集合是無序的(非線性序列)。set的定義(初始化):s = set()s = {1, 2, 3}增加元素:添加的元素必須是可hash的,list、set、bytearray、dict是不可hash的,所以不能作為set的元素,通常來說內置類型不能變的都是可hash的。add方法:添加一個元素到集合,如果該元素在集合已經存在,集合不會發生任何改變(集合的元素都是唯一的)。add(...)Add an element to a set.This has no effect if the element is already present. >>> s = {1, 2, 3}>>> s.add(4)>>> s{1, 2, 3, 4}>>> s.add(2)>>> s{1, 2, 3, 4}update方法:將一個可迭代對象更新到集合。update(...)Update a set with the union of itself and others. >>> s{1, 2, 3, 4}>>> s.update({4, 5, 6})>>> s{1, 2, 3, 4, 5, 6}>>> s.update([1, 22 ,11])>>> s{1, 2, 3, 4, 5, 6, 22, 11}>>> s.update('python')>>> s{1, 2, 3, 4, 5, 6, 11, 22, 'h', 'n', 'y', 'p', 'o', 't'}>>> s.update({'a':1, 'b':2}) >>> s{1, 2, 3, 4, 5, 6, 'b', 11, 22, 'a', 'h', 'n', 'y', 'p', 'o', 't'} #update字典時只會添加字典的key到集合。>>> 刪除元素:remove方法:刪除集合的一個元素,如果該元素不存在,則拋出一個KeyError異常。remove(...)Remove an element from a set; it must be a member.If the element is not a member, raise a KeyError.>>> s{1, 2, 3, 4, 5, 6, 'b', 11, 22, 'a', 'h', 'n', 'y', 'p', 'o', 't'}>>> s.remove(1)>>> s{2, 3, 4, 5, 6, 'b', 11, 22, 'a', 'h', 'n', 'y', 'p', 'o', 't'}>>> s.remove(100)Traceback (most recent call last):File "<stdin>", line 1, in <module>KeyError: 100>>> discard方法:刪除集合的一個元素,如果該元素不存在,則什么都不做。discard(...)Remove an element from a set if it is a member.If the element is not a member, do nothing.>>> s{2, 3, 4, 5, 6, 'b', 11, 22, 'a', 'h', 'n', 'y', 'p', 'o', 't'}>>> s.discard(2)>>> s{3, 4, 5, 6, 'b', 11, 22, 'a', 'h', 'n', 'y', 'p', 'o', 't'}>>> s.discard(200)>>> pop方法:隨機刪除集合的一個元素,并返回該元素,如果集合為空則拋出一個KeyError異常。pop(...)Remove and return an arbitrary set element.Raises KeyError if the set is empty.>>> s{1, 2, 3}>>> s.pop()1>>> s.pop()2>>> s.pop()3>>> s.pop()Traceback (most recent call last):File "<stdin>", line 1, in <module>KeyError: 'pop from an empty set'>>> clear方法:刪除集合的所有元素。clear(...)Remove all elements from this set.>>> s{1, 2, 3}>>> s.clear()>>> sset()>>> 修改元素和查找元素:沒有任何方法可以直接修改和查找集合中的某個具體元素,因為集合是無序的,所以沒有任何方法能夠定位到集合某個元素的位置。訪問方法:集合是可迭代對象,可以使用成員運算符(in、 not in)可以使用for in的方式訪問集合線性結構的成員運算,時間復雜度是O(n),集合的成員運算,時間復雜度是O(1)額外拓展:時間復雜度效率排列:O(1) 常數復雜度O(logn) 對數復雜度O(n) 線性復雜度O(n^2) 平方復雜度O(n^3)O(2^n) 指數復雜度O(n!) 階乘復雜度
?
轉載于:https://www.cnblogs.com/LouisZJ/p/5685799.html
與50位技術專家面對面20年技術見證,附贈技術全景圖總結
以上是生活随笔為你收集整理的2016.07.17-18 集合方法的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 信用卡逾期影响出行吗
- 下一篇: 上学路线 (Standard IO)