python基礎系列(三)---set、collection、深淺拷貝


 

以下所有內容均為作者原創,歡迎轉載,但是轉載時請注明出處!

 

set集合

set是一個無序且不重復的元素的集合。

常用方法:

a={1,2,3,4,5}

b={3,4,5,6,7}

a.add():添加元素

a.clear():清空元素

a.copy():淺copy

a.difference(b):同集合b比較,返回一個在b集合中沒有的元素集合,a集合不變

a.difference_update(b):同集合b比較,a集合改變為   去掉所有跟b集合一樣的元素   的集合

a.discard(指定的元素):去除a中指定的元素,如果元素不存在,則do nothing

a.intersection(b):返回a和b的交集,a不變

a.intersection_update(b):取a和b的交集,a改變為交集

a.isdisjoint(b):是否有和b有交集,沒有交集返回True

a.issbuset(b):a是否是b的子集,是返回True

a.issuperset(b):a是否是b的父集,是返回True

a.pop():刪除並返回一個隨機的元素,不能指定元素,如果集合為空,返回KeyError

a.remove(指定元素):刪除一個元素

a.symmetric_difference(b):返回a和b中不交叉的元素的集合,a不變

a.symmetric_difference_update(b):a集合變為a和b不交叉的元素的新集合

a.union(b):返回a和b的並集,a不變

a.update(b):a變為a和b的並集

 

collection-對字典擴展

使用collection需要手動導入,import collection 

一、計數器(Counter)

計數器是對字典類型的補充,用於追蹤值的出現次數,可以追終字符串、元組、列表中的元素

import collections

a=collections.Counter()

a.update('asdfasdfasdfasdfasdfgdfs')

print(a)
#結果如下
Counter({'f': 6, 'd': 6, 's': 6, 'a': 5, 'g': 1})

a.update([1,1,2,3,4,3,4,53,5,32,23,23,])
#結果如下:
Counter({'d': 6, 'f': 6, 's': 6, 'a': 5, 1: 2, 3: 2, 23: 2, 4: 2, 32: 1, 2: 1, 'g': 1, 5: 1, 53: 1})

方法說明:

還以上面代碼中的a對象為例。

a.__missing__():默認方法,元素不存在,返回值為0

a.elements():列出所有元素

a.most_common():列出前n位最多的元素統計

a.copy():淺拷貝

a.update(元素):在原來元素的基礎上新增元素

a.substract(元素):在原來元素的基礎上減少參數中對應元素的數量

二、有序字典(orderedDict)

orderedDict是對字典類型的補充,他記住了字典元素的添加順序。

orderedDict有序字典的創建原理其實就是python內部將key創建為一個列表,然后循環這個列表,去取對應的value值因為列表是有序的,所以讀到的value也是有序的。

三、默認字典(defaultdict)

默認字典可以在創建字典時給字典中的value設置默認的數據類型,這樣可以在以后訪問字典時按字典中的默認順序遍歷。

a=collections.defaultdict(list)

這樣就可以直接使用a.append()方法。

四、可命名元組(namedtuple)

namedtuple的功能是可以讓元組中的元素訪問時直接使用元素的名字而非下標訪問。是對元組的擴展

使用示例:

mytuple=collections.namedtuple('tuplename',['x','y','z'])

實際上mytuple相當於一個class,還需要實例化:

import collections

mytuple=collections.namedtuple('tuplename',['x','y','z'])
a=mytuple(1,2,4)
print(a.x)
print(a.y)
print(a.z)

五、隊列(雙向deque,單向quque)

deque:兩端都可以操作的序列,可以在序列前后中間任意位置執行添加或刪除.有點兒像list

創建一個隊列

d=deque()

隊列的方法有:

def append(self, *args, **kwargs): # real signature unknown
        """ Add an element to the right side of the deque. """
        pass

    def appendleft(self, *args, **kwargs): # real signature unknown
        """ Add an element to the left side of the deque. """
        pass

    def clear(self, *args, **kwargs): # real signature unknown
        """ Remove all elements from the deque. """
        pass

    def count(self, value): # real signature unknown; restored from __doc__
        """ D.count(value) -> integer -- return number of occurrences of value """
        return 0

    def extend(self, *args, **kwargs): # real signature unknown
        """ Extend the right side of the deque with elements from the iterable """
        pass

    def extendleft(self, *args, **kwargs): # real signature unknown
        """ Extend the left side of the deque with elements from the iterable """
        pass

    def pop(self, *args, **kwargs): # real signature unknown
        """ Remove and return the rightmost element. """
        pass

    def popleft(self, *args, **kwargs): # real signature unknown
        """ Remove and return the leftmost element. """
        pass

    def remove(self, value): # real signature unknown; restored from __doc__
        """ D.remove(value) -- remove first occurrence of value. """
        pass

    def reverse(self): # real signature unknown; restored from __doc__
        """ D.reverse() -- reverse *IN PLACE* """
        pass


d = deque(maxlen=30)可以限制序列的長度

quue:先進先出

定義一個單向隊列

import queue
myqueue = Queue.Queue(maxsize = 10)

Queue.Queue類即是一個隊列的同步實現。隊列長度可為無限或者有限。可通過Queue的構造函數的可選參數maxsize來設定隊列長度。如果maxsize小於1就表示隊列長度無限。

a=queue.Queue()

a.empty():判斷隊列是否為空

a.full():判斷隊列是否為滿

a.pop():從隊列頭刪除一個元素並返回

a.put(i):放一個值到隊列的尾部

三、深淺copy

 

一般數據類型中的copy訪問(obj.copy())為淺copy,數字和字符串不受深淺copy影響。

深copy需要導入copy模塊

import copy

copy.deepcopy()

 

深淺copy其實可以這樣理解,所謂淺拷貝就是對引用的拷貝,所謂深拷貝就是對對象的資源的拷貝。

淺copy后如果修改copy后的數據會對原數據同步更改,深copy不會。

實際上是淺copy只是copy了第一層地址,深copy是重新開辟內存空間,所以深copy后修改數據不會對copy源的數據造成影響。

如果日后有遺忘可參考:http://www.cnblogs.com/zhaojianbo/p/5137026.html

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM