python中的collestions模块

看到collections.namedtuple()函数,顺便学习一下

1.namedtuple

创建一个具名元组子类,可以使用名字(属性)来引用元组中的值

>>> import collections
>>> node = collections.namedtuple('position',['x','y'])
>>> node
<class '__main__.position'>
>>> p = node(1,5)
>>> p
position(x=1, y=5)
>>> p.x
1
>>> p.y
5

2.Counter

创建一个字典子类,用于计数,统计字符(特定对象)出现的次数
>>> url = 'http://write.blog.csdn.net/postedit'
>>> counter = collections.Counter()
>>> for i in url:
	counter[i] += 1

	
>>> counter
Counter({'t': 6, '/': 3, 'e': 3, '.': 3, 'p': 2, 'i': 2, 'o': 2, 's': 2, 'd': 2, 'n': 2, 'h': 1, ':': 1, 'w': 1, 'r': 1, 'b': 1, 'l': 1, 'g': 1, 'c': 1})


3.defaultdict

创建一个带有默认值的字典,如果引用时key不存在,则返回默认值
>>> d_dict = collections.defaultdict(lambda:'no key')
>>> d_dict[1] = 1
>>> d_dict[1]
1
>>> d_dict[2]
'no key'


4.deque

创建一个双向队列(列表),可以从队列的两侧添加或删除元素
>>> d_q = collections.deque([1,2,3])
>>> d_q.append(4)
>>> d_q
deque([1, 2, 3, 4])
>>> d_q.appendleft(4)
>>> d_q
deque([4, 1, 2, 3, 4])
>>> d_q.popleft()
4
>>> d_q
deque([1, 2, 3, 4])


5.OrderedDict

创建一个Key排列有序的字典,顺序为Key加入的顺序

puthon3.6之后常规的 dict( ) 中的键也是有序的了,看起来没什么作用

https://docs.python.org/3.6/whatsnew/3.6.html#new-dict-implementation
这里说: The order-preserving aspect of this new implementation is considered an implementation detail and should not be relied upon


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值