Python中collections類使用(1)

2021-10-04 12:05:56 字數 2918 閱讀 6338

counter是乙個dict子類,主要是用來對需要訪問的物件的頻率進行計數。在collections類中用的也是比較多的一種操作方式。

from collections import counter

colors =

['red'

,'blue'

,'red'

,'green'

,'blue'

,'blue'

]c = counter(colors)

print

(dict

(c))--

----

---# 輸出結果

>>--

----

---c1=counter(

"hello world"

)print

("c1:"

)print

(dict

(c1)

)c2=counter(

"how are you thank you"

.split())

print

("c2:"

)print

(dict

(c2)

)list

(c2.elements())

#獲取元素

#輸出》c1:

>>

>>c2:

>>

>>

['how'

,'are'

,'you'

,'you'

,'thank'

]

cnt = counter(

)# 傳進空值

c = counter(

'gallahad'

)# 傳進字串

c = counter(

)# 傳進字典

c = counter(cats=

4, dogs=8)

# 傳進元組

c = counter(a=

3, b=1)

d = counter(a=

1, b=2)

c['a'

]#獲取元素值

#3c + d # 相加

#counter()

c - d # 相減,如果小於等於0,刪去

#counter()

c & d # 求最小

#counter()

c | d # 求最大

#counter()

sc=counter(

'abracadabra'

).most_common(3)

#求元素值最多的前幾位

#[('a', 5), ('b', 2), ('r', 2)]

deque是雙邊佇列,可以從左右兩邊載入刪除元素,結合了棧和佇列的特點,可以在python中直接呼叫,在一些演算法問題上有很好的應用。

clear():清楚所有元素,長度變為0

copy():建立乙份淺拷貝

count(x):計算佇列中個數等於x的元素

extend(iterable):在佇列右側新增iterable中的元素

extendleft(iterable):在佇列左側新增iterable中的元素,注:在左側新增時,iterable引數的順序將會反過來新增

index(x[,start[,stop]]):返回第 x 個元素(從 start 開始計算,在 stop 之前)。返回第乙個匹配,如果沒找到的話,公升起 valueerror 。

insert(i,x):在位置 i 插入 x 。注:如果插入會導致乙個限長deque超出長度 maxlen 的話,就公升起乙個 indexerror 。

pop():移除最右側的元素

popleft():移除最左側的元素

remove(value):移去找到的第乙個 value。沒有丟擲valueerror

reverse():將deque逆序排列。返回 none 。

maxlen:佇列的最大長度,沒有限定則為none。

import collections

d = collections.deque(

)'a'

)# 在最右邊新增乙個元素,此時 d=deque('a')

'b')

# 在最左邊新增乙個元素,此時 d=deque(['b', 'a'])

d.extend(

['c'

,'d'])

# 在最右邊新增所有元素,此時 d=deque(['b', 'a', 'c', 'd'])

d.extendleft(

['e'

,'f'])

# 在最左邊新增所有元素,此時 d=deque(['f', 'e', 'b', 'a', 'c', 'd'])

d.pop(

)# 將最右邊的元素取出,返回 'd',此時 d=deque(['f', 'e', 'b', 'a', 'c'])

d.popleft(

)# 將最左邊的元素取出,返回 'f',此時 d=deque(['e', 'b', 'a', 'c'])

d.rotate(-2

)# 向左旋轉兩個位置(正數則向右旋轉),此時 d=deque(['a', 'c', 'e', 'b'])

d.count(

'a')

# 佇列中'a'的個數,返回 1

d.remove(

'c')

# 從佇列中將'c'刪除,此時 d=deque(['a', 'e', 'b'])

d.reverse(

)# 將佇列倒序,此時 d=deque(['b', 'e', 'a'])

webcontrol中的collection屬性

今天可以說是費了九牛二虎之力,通宵一晚,才研究出這個webcontrol的collection屬性的設定.首先介紹幾個屬性上的attribute 1 designerserializationvisibility 常用的是designerserializationvisibility designe...

python常用內建模組 collections

1.namedtuple namedtuple是乙個函式,它用來建立乙個自定義的tuple物件,並且規定了tuple元素的個數,並可以用屬性而不是索引來引用tuple的某個元素。這樣一來,我們用namedtuple可以很方便地定義一種資料型別,它具備tuple的不變性,又可以根據屬性來引用,使用十分...

Python容器資料型別 collections

usr bin python coding utf 8 count物件 only 2.7 from collections import counter 統計字母出現的次數 counter hello world counter red blue red green blue blue 小於等於0的...