2016.07.17-18 集合方法
生活随笔
收集整理的這篇文章主要介紹了
2016.07.17-18 集合方法
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
集合(set):特性:1.集合的元素都是唯一的。2.集合是無(wú)序的(非線性序列)。set的定義(初始化):s = set()s = {1, 2, 3}增加元素:添加的元素必須是可hash的,list、set、bytearray、dict是不可hash的,所以不能作為set的元素,通常來(lái)說(shuō)內(nèi)置類(lèi)型不能變的都是可hash的。add方法:添加一個(gè)元素到集合,如果該元素在集合已經(jīng)存在,集合不會(huì)發(fā)生任何改變(集合的元素都是唯一的)。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方法:將一個(gè)可迭代對(duì)象更新到集合。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字典時(shí)只會(huì)添加字典的key到集合。>>> 刪除元素:remove方法:刪除集合的一個(gè)元素,如果該元素不存在,則拋出一個(gè)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方法:刪除集合的一個(gè)元素,如果該元素不存在,則什么都不做。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方法:隨機(jī)刪除集合的一個(gè)元素,并返回該元素,如果集合為空則拋出一個(gè)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()>>> 修改元素和查找元素:沒(méi)有任何方法可以直接修改和查找集合中的某個(gè)具體元素,因?yàn)榧鲜菬o(wú)序的,所以沒(méi)有任何方法能夠定位到集合某個(gè)元素的位置。訪問(wèn)方法:集合是可迭代對(duì)象,可以使用成員運(yùn)算符(in、 not in)可以使用for in的方式訪問(wèn)集合線性結(jié)構(gòu)的成員運(yùn)算,時(shí)間復(fù)雜度是O(n),集合的成員運(yùn)算,時(shí)間復(fù)雜度是O(1)額外拓展:時(shí)間復(fù)雜度效率排列:O(1) 常數(shù)復(fù)雜度O(logn) 對(duì)數(shù)復(fù)雜度O(n) 線性復(fù)雜度O(n^2) 平方復(fù)雜度O(n^3)O(2^n) 指數(shù)復(fù)雜度O(n!) 階乘復(fù)雜度
?
轉(zhuǎn)載于:https://www.cnblogs.com/LouisZJ/p/5685799.html
與50位技術(shù)專(zhuān)家面對(duì)面20年技術(shù)見(jiàn)證,附贈(zèng)技術(shù)全景圖總結(jié)
以上是生活随笔為你收集整理的2016.07.17-18 集合方法的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 信用卡逾期影响出行吗
- 下一篇: 上学路线 (Standard IO)