python重要的幾個內置函數用法

        python內置了很多可以供我們直接調用的函數,這些函數的效率往往都非常高,我們在自己造輪子的同時,也非常有必要了解並且正確使用python給我們提供的大量的內置函數,在前面的博客裏面我已經介紹了幾個比較常用的函數,這裏再介紹幾個,它們分別是collections模塊下的 Counter函數,deque函數以及defaultdict函數。

      1)Counter函數。Counter函數主要可以用來確定某個可迭代對象裏面所有元素出現的次數,常用的可迭代對象一般是list。所以如果傳給Counter函數的參數不是可迭代對象的時候,會報錯。當然我們也可以使用count函數求出list中某個元素出現的次數。代碼如下:

    

from random import sample
from collections import Counter, deque, defaultdict

data = sample(range(0, 10, 1), 6) + sample(range(0, 10, 1), 6)  # list的拼接
item_counts = Counter(data)  # Counter的參數應該是一個可以迭代的對象.可迭代的對象:dict,tuple, dict
print(item_counts)
結果:Counter({3: 2, 4: 2, 7: 2, 8: 2, 2: 1, 5: 1, 6: 1, 9: 1})

大家可以發現Counter函數產生的結果是個字典,字典,字典!是傳入的列表中的各個元素,是該元素出現的次數,次數,次數!我們可以很容易的獲取裏面的元素。

for key, value in item_counts.items():
    print(key, value)
key = item_counts.keys()
value = item_counts.values()
print(key, value)
[9, 1, 0, 4, 7, 5, 3, 5, 6, 2, 0, 1]
Counter({0: 2, 1: 2, 5: 2, 2: 1, 3: 1, 4: 1, 6: 1, 7: 1, 9: 1})
0 2
1 2
2 1
3 1
4 1
5 2
6 1
7 1
9 1
dict_keys([0, 1, 2, 3, 4, 5, 6, 7, 9]) dict_values([2, 2, 1, 1, 1, 2, 1, 1, 1])

        使用count函數同樣可以實現以上的效果,代碼如下:

data = sample(range(0, 10, 1), 6) + sample(range(0, 10, 1), 6)  # list的拼接
item_counts = list(map(lambda x: {x: data.count(x)}, set(data)))
print(data)
print(item_counts)
結果:[0, 4, 7, 8, 9, 3, 3, 4, 7, 1, 0, 6]
      [{0: 2}, {1: 1}, {3: 2}, {4: 2}, {6: 1}, {7: 2}, {8: 1}, {9: 1}]
        2)deque函數。deque函數是一個雙端隊列,實質上可以理解成是一個list。只不過可以很方便的進行頭尾刪除、插入等操作。但是刪除,插入,遍歷deque的時候,如果完全使用list相同的方式.
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章