Python中高階容器

2021-09-29 06:50:00 字數 2590 閱讀 6045

'''python 中常見的容器為 list set dict tuple 這裡主要探索下不常見的容器'''

#@author jiangnan he

#list set dict tuple

import queue#佇列

import heapq#優先佇列 實現堆排序 大小堆

from collections import deque#雙端佇列

from collections import counter#計數器 dict字典子類

from collections import defaultdict# dict 字典子類

print

("############### queue#############################"

)#queue

'''queue.queue() 構建乙個佇列

put()隊尾新增元素

get()獲取隊首元素

empty()判斷是否為空

'''a=queue.queue(

)for i in

range(10

):a.put(i)

while

not a.empty():

print

(a.get())

print

("###################### deqeu ###########################"

)#deque 雙端佇列支援操作很多

"""deque與c++ 中的list對比

deque() 構建乙個deque雙端佇列

extend() extendleft()新增乙個列表

remove(obj)移除某元素 copy()淺拷貝

clear()清空deque reverse()反轉 rotate(int)右邊int個元素放到左邊 insert(index,obj)

"""b=deque(

)for i in

range(2

,10):

while b:

# 無需empty判斷

print

(b.popleft())

b.clear(

)print

("###################### counter #########################"

)'''

可以對列表和字串計數

most_common(n) 出現最多的n個元素

get(key)返回value

update('str')#在原字典中增數

subtract('str')#在原字典中減數

elements()返回迭代器

'''l=

"dfbadshbsdbfjsadbajds"

d=counter(l)

print

(d.most_common(4)

)#返回前4個計數高的

for key in d.keys():

print

(key,d[key]

)d.update(

"zzz"

)#增加zzz

print

(d)print

(list

(d.elements())

)d.subtract(

"zzz"

)#減去zzz

print

(d)print

(list

(d.elements())

)print

("###################### defaultdict #########################"

)dic=defaultdict(

list

)#乙個key對應乙個list

s =[

('python',1

),('swift',2

),('python',3

),('swift',4

),('python',9

)]# 建立defaultdict,設定由list()函式來生成預設值

d = defaultdict(

list

)for k, v in s:

# 直接訪問defaultdict中指定key對應的value即可。

# 如果該key不存在,defaultdict會自動為該key生成預設值

d[k]

print

(list

(d.items())

)print

("###################### heapq #########################"

)'''

heapq.heapify()#無返回值

'''s=[9

,8,2

,3,5

,7,6

,1,4

]heapq.heapify(s)

print

(s)print

)#此時彈出第乙個元素0)

#往堆裡面加乙個元素 維持小堆

print

(s)

python中高階函式

一等公民 高階函式 高階函式 high order function def counter base def inc step 1 nonlocal base base step return base return inc 上面的counter是高階函式,因為return inc,即返回函式 內...

Python 開發中高階技巧

chars c for c in python chars p y t h o n dict1 double dict1 double dict1 set1 double set double set x y z z nums 1,2,3 nums 1,2,3 copy nums nums copy...

Python的學習 Python中高階函式的應用

變數可以指向函式,函式的引數能接收變數,那麼乙個函式就可以接收另乙個函式作為引數,這種函式就稱之為高階函式。map 函式接收兩個引數,乙個是函式,乙個是序列 map將傳入的函式依次作用到序列的每個元素,並把結果作為新的序列返回 序列 1,2,3,4 的每個元素求絕對值 print list map ...