1. 程式人生 > >Python高級數據結構(一)

Python高級數據結構(一)

1.3 tdi arr cat rate err 因此 try 參考

數據結構

數據結構的概念很好理解,就是用來將數據組織在一起的結構。換句話說,數據結構是用來存儲一系列關聯數據的東西。在Python中有四種內建的數據結構,分別是List、Tuple、Dictionary以及Set。大部分的應用程序不需要其他類型的數據結構,但若是真需要也有很多高級數據結構可供選擇,例如Collection、Array、Heapq、Bisect、Weakref、Copy以及Pprint。本文將介紹這些數據結構的用法,看看它們是如何幫助我們的應用程序的。

關於四種內建數據結構的使用方法很簡單,並且網上有很多參考資料,因此本文將不會討論它們。

1. Collections

1.1 Counter()

如果你想統計一個單詞在給定的序列中一共出現了多少次,諸如此類的操作就可以用到Counter。來看看如何統計一個list中出現的item次數:

from collections import Counter
 
li = ["Dog", "Cat", "Mouse", 42, "Dog", 42, "Cat", "Dog"]
a = Counter(li)
print a 
#Counter({‘Dog‘: 3, 42: 2, ‘Cat‘: 2, ‘Mouse‘: 1})

若要統計一個list中不同單詞的數目,可以這麽用:

from collections import Counter
 
li = ["Dog", "Cat", "Mouse", 42, "Dog", 42, "Cat", "Dog"]
a = Counter(li)
print a # Counter({‘Dog‘: 3, 42: 2, ‘Cat‘: 2, ‘Mouse‘: 1})
 
print len(set(li)) # 4

如果需要對結果進行分組,可以這麽做:

from collections import Counter
 
li = ["Dog", "Cat", "Mouse","Dog","Cat", "Dog"]
a = Counter(li)
 
print a # Counter({‘Dog‘: 3, ‘Cat‘: 2, ‘Mouse‘: 1})
 
print "{0} : {1}".format(a.values(),a.keys())  # [1, 3, 2] : [‘Mouse‘, ‘Dog‘, ‘Cat‘]
 
print(a.most_common(3)) # [(‘Dog‘, 3), (‘Cat‘, 2), (‘Mouse‘, 1)]
1.2 deque

deque即雙頭隊列,隊列元素能夠在隊列兩端添加或刪除。Deque支持線程安全的,經過優化的append和pop操作,在隊列兩端的相關操作都能達到近乎O(1)的時間復雜度

以下的例子是執行基本的隊列操作:

from collections import deque
q = deque(range(5))
q.append(5)
q.appendleft(6)
print q
print q.pop()
print q.popleft()
print q.rotate(3)
print q
print q.rotate(-1)
print q
 
# deque([6, 0, 1, 2, 3, 4, 5])
# 5
# 6
# None
# deque([2, 3, 4, 0, 1])
# None
# deque([3, 4, 0, 1, 2])
1.3 defaultdict

當查找一個不存在的鍵操作發生時,它的default_factory會被調用,提供一個默認的值,並將這對鍵值存儲下來。其他的參數同普通的字典一致。

defaultdict對象可以用來追蹤單詞的位置,如:

from collections import defaultdict
 
s = "the quick brown fox jumps over the lazy dog"
 
words = s.split()
location = defaultdict(list)
for m, n in enumerate(words):
    location[n].append(m)
 
print location
 
# defaultdict(<type ‘list‘>, {‘brown‘: [2], ‘lazy‘: [7], ‘over‘: [5], ‘fox‘: [3],
# ‘dog‘: [8], ‘quick‘: [1], ‘the‘: [0, 6], ‘jumps‘: [4]})

是選擇lists或sets與defaultdict搭配取決於你的目的,使用list能夠保存你插入元素的順序,而使用set則不關心元素插入順序,它會幫助消除重復元素。

from collections import defaultdict
 
s = "the quick brown fox jumps over the lazy dog"
 
words = s.split()
location = defaultdict(set)
for m, n in enumerate(words):
    location[n].add(m)
 
print location
 
# defaultdict(<type ‘set‘>, {‘brown‘: set([2]), ‘lazy‘: set([7]),
# ‘over‘: set([5]), ‘fox‘: set([3]), ‘dog‘: set([8]), ‘quick‘: set([1]),
# ‘the‘: set([0, 6]), ‘jumps‘: set([4])})

另一種創建multidict的方法:

s = "the quick brown fox jumps over the lazy dog"
d = {}
words = s.split()
 
for key, value in enumerate(words):
    d.setdefault(key, []).append(value)
print d
 
# {0: [‘the‘], 1: [‘quick‘], 2: [‘brown‘], 3: [‘fox‘], 4: [‘jumps‘], 5: [‘over‘], 6: [‘the‘], 7: [‘lazy‘], 8: [‘dog‘]}

一個更復雜的例子:

class Example(dict):
    def __getitem__(self, item):
        try:
            return dict.__getitem__(self, item)
        except KeyError:
            value = self[item] = type(self)()
            return value
 
a = Example()
 
a[1][2][3] = 4
a[1][3][3] = 5
a[1][2][‘test‘] = 6
 
print a # {1: {2: {‘test‘: 6, 3: 4}, 3: {3: 5}}}

Python高級數據結構(一)