python-collections模組

來源:互聯網
上載者:User

標籤:有序   efault   print   參考   http   point   color   dict   font   

在collections中提供了如下的類:[‘deque‘, ‘defaultdict‘, ‘namedtuple‘, ‘UserDict‘, ‘UserList‘,‘UserString‘, ‘Counter‘, ‘OrderedDict‘, ‘ChainMap‘]

1.namedtuple(): 產生可以使用名字來訪問元素內容的tuple子類
2.deque: 雙端隊列,可以快速的從另外一側追加和推出對象
3.Counter: 計數器,主要用來計數
4.OrderedDict: 有序字典
5.defaultdict: 帶有預設值的字典

參考部落格:http://www.cnblogs.com/liupengpengg/p/5593273.html

預設字典

  可以指定字典中值的類型

例如:將[11,22,33,44,55,66,77,88,99]中大於55的數放在‘k1’中,小雨等於55的放在‘k2’中。

from collections import defaultdict

v=[11,22,33,44,55,66,77,88,99]

dic=defaultdict(list)

for i in v:

  if i >55:

    dic[‘k1‘].append(i)

  else:

  dic[‘k2‘].append(i)

print(dic)

結果:defaultdict(<class ‘list‘>, {‘k2‘: [11, 22, 33, 44, 55], ‘k1‘: [66, 77, 88, 99]})

可命名元組

可命名並不是說元組中的元素可以進行修改,是可以將元組中的每個元素指定一個代號,以後就可以通過這個代號來尋找這個元素,而不是通過索引。需要注意的是:要用這個類我們需要先建立類,

例如:通過x,y,z來取出元組中的值

from collections import namedtuple

point=namedtuple(‘point‘,[‘x‘,‘y‘,‘z‘])

a=point(11,22,33)

print(a.x,a.y,a.z)

結果:11 22 33

python-collections模組

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.