二、collections

collections是对Python现有的数据类型的补充,在使用collections中的对象要先导入import collections模块

1、Counter——计数器

1.1 Counter说明及定义

计数器是对字典的补充,继承自字典对象,也就是说除了具有字典的所有方法外,还有很多扩展的功能

定义Counter对象

Counter接受一个序列对象如列表、元祖、字符串等,返回成员出现的以成员为key出现次数value的字典(按照出现的次数的倒序排列)

>>> c = collections.Counter("adfawreqewradfa")
>>> c
Counter({'a': 4, 'd': 2, 'e': 2, 'r': 2, 'w': 2, 'f': 2, 'q': 1})
>>> c2 = collections.Counter(['zhang', 'tom', 'peter', 'zhang'])
>>> c2
Counter({'zhang': 2, 'peter': 1, 'tom': 1})

1.2 Couter常用方法

1)most_common——返回前几个的元素和对应出现的次数(按照出现次数的倒序排列)

代码:

 def most_common(self, n=None):
'''List the n most common elements and their counts from the most
common to the least. If n is None, then list all element counts. >>> Counter('abcdeabcdabcaba').most_common(3)
[('a', 5), ('b', 4), ('c', 3)] '''
# Emulate Bag.sortedByCount from Smalltalk
if n is None:
return sorted(self.items(), key=_itemgetter(1), reverse=True)
return _heapq.nlargest(n, self.items(), key=_itemgetter(1))

示例:

Counter({'a': 4, 'd': 2, 'e': 2, 'r': 2, 'w': 2, 'f': 2, 'q': 1})
>>> c.most_common(3)
[('a', 4), ('d', 2), ('e', 2)]
>>> c.most_common(2)
[('a', 4), ('d', 2)]

2)elements——返回所有元素,迭代器对象

代码:

 def elements(self):
'''Iterator over elements repeating each as many times as its count. >>> c = Counter('ABCABC')
>>> sorted(c.elements())
['A', 'A', 'B', 'B', 'C', 'C'] # Knuth's example for prime factors of 1836: 2**2 * 3**3 * 17**1
>>> prime_factors = Counter({2: 2, 3: 3, 17: 1})
>>> product = 1
>>> for factor in prime_factors.elements(): # loop over factors
... product *= factor # and multiply them
>>> product
1836 Note, if an element's count has been set to zero or is a negative
number, elements() will ignore it. '''
# Emulate Bag.do from Smalltalk and Multiset.begin from C++.
return _chain.from_iterable(_starmap(_repeat, self.items())) # Override dict methods where necessary

示例:

>>> c = collections.Counter("adfawreqewradfa")
>>> c
Counter({'a': 4, 'd': 2, 'e': 2, 'r': 2, 'w': 2, 'f': 2, 'q': 1})
>>> c.elements()
<itertools.chain object at 0x7f63c8b0beb8>
>>> list(c.elements())
['d', 'd', 'q', 'e', 'e', 'r', 'r', 'w', 'w', 'f', 'f', 'a', 'a', 'a', 'a']

注意:返回的是一个迭代器对象,可以通过内置方法将其转化为列表对象,也可以字节通过for in进行遍历

3)update——添加一个新的成员,如果存在计数器的值进行累加,如果不存在将新建一个成员

代码:

 def update(*args, **kwds):
'''
类似字典的update方法,添加一个成员的同时计数器会进行累加
Like dict.update() but add counts instead of replacing them. Source can be an iterable, a dictionary, or another Counter instance. >>> c = Counter('which')
>>> c.update('witch') # add elements from another iterable
>>> d = Counter('watch')
>>> c.update(d) # add elements from another counter
>>> c['h'] # four 'h' in which, witch, and watch
4 '''
# The regular dict.update() operation makes no sense here because the
# replace behavior results in the some of original untouched counts
# being mixed-in with all of the other counts for a mismash that
# doesn't have a straight-forward interpretation in most counting
# contexts. Instead, we implement straight-addition. Both the inputs
# and outputs are allowed to contain zero and negative counts. if not args:
raise TypeError("descriptor 'update' of 'Counter' object "
"needs an argument")
self, *args = args
if len(args) > 1:
raise TypeError('expected at most 1 arguments, got %d' % len(args))
iterable = args[0] if args else None
if iterable is not None:
if isinstance(iterable, Mapping):
if self:
self_get = self.get
for elem, count in iterable.items():
self[elem] = count + self_get(elem, 0)
else:
super(Counter, self).update(iterable) # fast path when counter is empty
else:
_count_elements(self, iterable)
if kwds:
self.update(kwds)

示例:

>>> c = collections.Counter(['zhang', 'peter', 'tom', 'zhang'])
>>> c
Counter({'zhang': 2, 'peter': 1, 'tom': 1})
>>> c.update('peter')
>>> c
Counter({'zhang': 2, 'e': 2, 'peter': 1, 't': 1, 'r': 1, 'tom': 1, 'p': 1}) # 注意参数是一个序列对象,如果传的是一个字符串,字符串的每一个字符都会被当成一个元素
>>> c = collections.Counter(['zhang', 'peter', 'tom', 'zhang'])
>>> c.update(['zhang'])
>>> c
Counter({'zhang': 3, 'peter': 1, 'tom': 1})

4)subtract——减去一个成员,计数器减1

代码:

 def subtract(*args, **kwds):
'''Like dict.update() but subtracts counts instead of replacing them.
Counts can be reduced below zero. Both the inputs and outputs are
allowed to contain zero and negative counts. Source can be an iterable, a dictionary, or another Counter instance. >>> c = Counter('which')
>>> c.subtract('witch') # subtract elements from another iterable
>>> c.subtract(Counter('watch')) # subtract elements from another counter
>>> c['h'] # 2 in which, minus 1 in witch, minus 1 in watch
0
>>> c['w'] # 1 in which, minus 1 in witch, minus 1 in watch
-1 '''
if not args:
raise TypeError("descriptor 'subtract' of 'Counter' object "
"needs an argument")
self, *args = args
if len(args) > 1:
raise TypeError('expected at most 1 arguments, got %d' % len(args))
iterable = args[0] if args else None
if iterable is not None:
self_get = self.get
if isinstance(iterable, Mapping):
for elem, count in iterable.items():
self[elem] = self_get(elem, 0) - count
else:
for elem in iterable:
self[elem] = self_get(elem, 0) - 1
if kwds:
self.subtract(kwds)

示例:

>>> c = collections.Counter(['zhang', 'peter', 'tom', 'zhang'])
>>> c
Counter({'zhang': 2, 'peter': 1, 'tom': 1})
>>> c.subtract(['zhang'])
>>> c
Counter({'peter': 1, 'tom': 1, 'zhang': 1})
>>> c.subtract(['zhang'])
>>> c.subtract(['zhang'])
>>> c
Counter({'peter': 1, 'tom': 1, 'zhang': -1})

注意:如果成员已经不存在了或者说为0了,计数器会继续递减,也就是说计数器有0和负数的概念的,但是使用elements显示的时候却没有该成员,如果计时器是0或者负数能说明这个成员出现过而已,另外如果为负数的时候,添加成员,成员不会真的添加到elements显示的成员中,直到计数器大于0为止

>>> list(c.elements())
['peter', 'tom']
>>> c.update(['zhang'])
>>> list(c.elements())
['peter', 'tom']
>>> c
Counter({'peter': 1, 'tom': 1, 'zhang': 0})

2、OrderedDict——有序字典

2.1 有序字典说明及定义

我们知道字典的是无顺序的,orderedDict就是对字典的扩展,使其有序,并且根据添加顺序进行排序

>>> oc = collections.OrderedDict()

当然我们也可以通过一个现有的字典进行初始化一个有序字典

>>> old_dic = {'a':1, 'b':2, 'c':3}
>>> new_dic = collections.OrderedDict(old_dic)>>> new_dic
OrderedDict([('b', 2), ('c', 3), ('a', 1)])

说明:由于old_dic是无序的,所以初始化的OrderedDict顺序并不是我们看到的定义old_dic时候的顺序,只是后面再添加成员的时候顺序是有保障的

>>> new_dic['d'] = 4
>>> new_dic['e'] = 5
>>> new_dic
OrderedDict([('b', 2), ('c', 3), ('a', 1), ('d', 4), ('e', 5)])

2.2 常用方法

1)clear——清空字典

代码:

 def clear(self): # real signature unknown; restored from __doc__
"""
清空字典
od.clear() -> None. Remove all items from od. """
pass

示例:

>>> dic = collections.OrderedDict({'a':1, 'b':2, 'c':3})
>>> dic
OrderedDict([('b', 2), ('c', 3), ('a', 1)])
>>> dic.clear()
>>> dic
OrderedDict()

2)keys——返回所有key组成的迭代对象

代码:

 def keys(self, *args, **kwargs): # real signature unknown
pass

示例:

>>> dic = collections.OrderedDict({'a':1, 'b':2, 'c':3})
>>> dic.keys()
KeysView(OrderedDict([('b', 2), ('c', 3), ('a', 1)]))

注意:返回的一个可迭代的对象,同样可以使用for in方法进行循环遍历,与原生字典不同的是有序字典返回的keys也是有序的

3)values——返回所有value组成的迭代对象

代码:

 def values(self, *args, **kwargs): # real signature unknown
pass

示例:

>>> dic = collections.OrderedDict({'a':1, 'b':2, 'c':3})
>>> dic.values()
ValuesView(OrderedDict([('b', 2), ('c', 3), ('a', 1)]))

说明:同样是有序的

4)items——返回key和value组成的迭代对象

代码:

 def items(self, *args, **kwargs): # real signature unknown
pass

示例:

>>> dic.items()
ItemsView(OrderedDict([('b', 2), ('c', 3), ('a', 1)]))

5)pop——删除指定key的元素

代码:

 def pop(self, k, d=None): # real signature unknown; restored from __doc__
"""
删除指定key的元素,并返回key所对应的值
k:要删除的元素的key
d:如果key不存在返回的默认值
od.pop(k[,d]) -> v, remove specified key and return the corresponding
value. If key is not found, d is returned if given, otherwise KeyError
is raised.
"""
pass

示例:

>>> dic = collections.OrderedDict({'a':1, 'b':2, 'c':3})
>>> dic
OrderedDict([('b', 2), ('c', 3), ('a', 1)])
>>> dic.pop('b')
2
>>> dic
OrderedDict([('c', 3), ('a', 1)])
>>> dic.pop('d', 10)
10

6)popitem——删除末尾的元素

代码:

 def popitem(self): # real signature unknown; restored from __doc__
"""
删除末尾的元素,并返回删除的元素的key和value
od.popitem() -> (k, v), return and remove a (key, value) pair.
Pairs are returned in LIFO order if last is true or FIFO order if false.
"""
pass

示例:

>>> dic = collections.OrderedDict({'a':1, 'b':2, 'c':3})
>>> dic
OrderedDict([('b', 2), ('c', 3), ('a', 1)])
>>> dic.popitem()
('a', 1)

说明:与原生字典不同的是,由于字典是有序的,所以删除不是随机的,而是删除排在最后的

7)setdefault——设置默认值

代码:

 def setdefault(self, k, d=None): # real signature unknown; restored from __doc__
"""
设置某个键的默认值,使用get方法如果该键不存在返回的值
od.setdefault(k[,d]) -> od.get(k,d), also set od[k]=d if k not in od """
pass

示例:同原生字典

8)update——将另一个字典更新到当前字典

代码

 def update(self, *args, **kwargs): # real signature unknown
pass

示例:同原生字典,不同的是有序和无序

9)move_to_end——将一个存在的元素移动到字典的末尾

代码:

 def move_to_end(self, *args, **kwargs): # real signature unknown
"""
移动一个元素到字典的末尾,如果该元素不存在这回抛出KeyError异常
Move an existing element to the end (or beginning if last==False). Raises KeyError if the element does not exist.
When last=True, acts like a fast version of self[key]=self.pop(key).
"""
pass

示例:

>>> dic = collections.OrderedDict({'a':1, 'b':2, 'c':3})
>>> dic
OrderedDict([('b', 2), ('c', 3), ('a', 1)])
>>> dic.move_to_end('b')
>>> dic
OrderedDict([('c', 3), ('a', 1), ('b', 2)])

3、defaultdict——默认字典

defaultdict是对字典的扩展,它默认个给字典的值设置了一种默认的数据类型,其他的均与原生字典一样

>>> ddic = collections.defaultdict(list) # 定义的时候需要指定默认的数据类型,这里指定的是列表类型
>>> ddic['k1'].append('a') # 尽管当前key还没有值,但是它默认已经是列表类型的类型,所以直接可以是用列表的append方法
>>> ddic
defaultdict(<class 'list'>, {'k1': ['a']})

4、namedtuple——可命名元祖

可命名元祖是元祖的扩展,包含所有元祖的方法的同时可以给每个元祖的元素命名,访问的时候也不需要在通过索引进行访问,直接通过元素名即可访问

>>> MytupleClass = collections.namedtuple('MytupleClass',['x', 'y', 'z'])
>>> mytup = MytupleClass(11,22,33)
>>> mytup.x
11
>>> mytup.y
22
>>> mytup.z
33

5、deque——双向队列

deque是一个线程安全的双向队列,类似列表,不同的是,deque是线程安全,并且是双向的也就是两边都可以进出

4.1 定义

d = collections.deque()

4.2 常用方法

1)append——从右边追加一个元素到队列的末尾

代码:

 def append(self, *args, **kwargs): # real signature unknown
"""
从右边追加一个元素到队列的末尾
Add an element to the right side of the deque. """
pass

示例:

>>> d = collections.deque([1, 2, 3])
>>> d
deque([1, 2, 3])
>>> d.append(4)
>>> d
deque([1, 2, 3, 4])

2)appendleft——从左边追加一个元素到队列的末尾

代码:

 def appendleft(self, *args, **kwargs): # real signature unknown
"""
从左边追加一个元素到队列的末尾
Add an element to the left side of the deque. """
pass

示例:

>>> d = collections.deque([1, 2, 3])
>>> d
deque([1, 2, 3])
>>> d.appendleft(4)
>>> d
deque([4, 1, 2, 3])

3)clear——清空队列

代码:

 def clear(self, *args, **kwargs): # real signature unknown
"""
清空队列
Remove all elements from the deque. """
pass

示例:

>>> d = collections.deque([1, 2, 3])
>>> d
deque([1, 2, 3])
>>> d.clear()
>>> d
deque([])

4)count——返回某个成员重复出现的次数

代码:

def count(self, value): # real signature unknown; restored from __doc__
"""
返回某个元素出现的次数
D.count(value) -> integer -- return number of occurrences of value """
return 0

示例:

>>> d = collections.deque([1, 2, 3, 2])
>>> d.count(2)
2

5)extend——从队列右边扩展一个可迭代的对象

代码:

 def extend(self, *args, **kwargs): # real signature unknown
"""
从队列右边扩展一个可迭代的对象
Extend the right side of the deque with elements from the iterable """
pass

示例:

>>> d = collections.deque([1, 2, 3])
>>> d
deque([1, 2, 3])
>>> d.extend([4, 5])
>>> d
deque([1, 2, 3, 4, 5])

6)extendleft——从队列左侧扩展一个可迭代的对象

代码:

 def extendleft(self, *args, **kwargs): # real signature unknown
"""
从队列左侧扩展一个可迭代对象
Extend the left side of the deque with elements from the iterable """
pass

示例:

>>> d = collections.deque([1, 2, 3])
>>> d
deque([1, 2, 3])
>>> d.extendleft([4, 5])
>>> d
deque([5, 4, 1, 2, 3])

7)index——查找并返回索引

代码:

 def index(self, value, start=None, stop=None): # real signature unknown; restored from __doc__
"""
查找元素是否存在,如果不存在将会抛出ValueError异常,如果存在返回第一找到的索引位置
value:要查找的元素
start:查找的开始所以你能
stop:查找的结束索引
D.index(value, [start, [stop]]) -> integer -- return first index of value.
Raises ValueError if the value is not present.
"""
return 0

说明:使用方法同列表,需要说明的是虽然是双向列表,但索引还是从左到右编码的

8)insert——插入索引

还没有实现

>>> d = collections.deque([1, 2, 3])
>>> d.insert(0, 4)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'collections.deque' object has no attribute 'insert'

9)pop——从队列右侧末尾删除一个元素,并返回该元素

代码:

 def pop(self, *args, **kwargs): # real signature unknown
"""
从队列右侧删除一个元素,并返回该元素
Remove and return the rightmost element. """
pass

示例:

>>> d = collections.deque([1, 2, 3])
>>> d.pop()
3

10)popleft——从队列左侧删除一个元素,并返回该元素

代码:

 def popleft(self, *args, **kwargs): # real signature unknown
"""
从队列的左侧删除一个元素,并返回该元素
Remove and return the leftmost element. """
pass

示例:

>>> d = collections.deque([1, 2, 3])
>>> d.popleft()
1

11)remove——删除一个元素

代码:

 def remove(self, value): # real signature unknown; restored from __doc__
"""
从队列左侧开始查找,并删除找到的第一个匹配的元素
D.remove(value) -- remove first occurrence of value. """
pass

示例:

>>> d = collections.deque([1, 2, 3, 2])
>>> d
deque([1, 2, 3, 2])
>>> d.remove(2)
>>> d
deque([1, 3, 2])

12)reverse——翻转队列

代码:

 def reverse(self): # real signature unknown; restored from __doc__
"""
翻转队列
D.reverse() -- reverse *IN PLACE* """
pass

示例:

>>> d = collections.deque([1, 2, 3])
>>> d.reverse()
>>> d
deque([3, 2, 1])

13)rotate——旋转队列

双向队列的旋转可以理解为,双向队列的首位是相连的环,旋转就是元素移动了多少个位置,如下图所示,或者说从左边取出元素追加到右边,追加了多少次

代码:

 def rotate(self, *args, **kwargs): # real signature unknown
"""
队列旋转,默认移动1位
Rotate the deque n steps to the right (default n=1). If n is negative, rotates left. """
pass

示例:

>>> d = collections.deque([1, 2, 3, 4, 5])
>>> d
deque([1, 2, 3, 4, 5])
>>> d.rotate(2)
>>> d
deque([4, 5, 1, 2, 3])

我的Python成长之路---第三天---Python基础(10)---2016年1月16日(雾霾)的更多相关文章

  1. 我的Python成长之路---第三天---Python基础(12)---2016年1月16日(雾霾)

    四.函数 日常生活中,要完成一件复杂的功能,我们总是习惯把“大功能”分解为多个“小功能”以实现.在编程的世界里,“功能”可称呼为“函数”,因此“函数”其实就是一段实现了某种功能的代码,并且可以供其它代 ...

  2. 我的Python成长之路---第三天---Python基础(11)---2016年1月16日(雾霾)

    三.深浅拷贝 在Python中将一个变量的值传递给另外一个变量通常有三种:赋值.浅拷贝以及深拷贝 讨论深浅拷贝之前我们把Python的数据类型分为基本数据类型包括数字.字符串.布尔以及None等,还有 ...

  3. 我的Python成长之路---第三天---Python基础(13)---2016年1月16日(雾霾)

    五.Python的常用的内置函数 Python为我们准备了大量的内置函数,如下图所示 这里我们只讨论红框内的内置函数 abs(x) 返回一个数的绝对值(模),参数可以是真说或浮点数 >>& ...

  4. 我的Python成长之路---第三天---Python基础(9)---2016年1月16日(雾霾)

    一.集合 set和dict类似,也是一组key的集合,但不存储value.由于key不能重复,所以,在set中,没有重复的key. 集合和我们数学中集合的概念是一样的,也有交集,并集,差集,对称差集等 ...

  5. 我的Python成长之路---第七天---Python基础(22)---2016年2月27日(晴)

    socket网络编程 socket通常也称作"套接字",用于描述IP地址和端口,是一个通信链的句柄,应用程序通常通过"套接字"向网络发出请求或者应答网络请求. ...

  6. python成长之路第三篇(1)_初识函数

    目录: 函数 为什么要使用函数 什么是函数 函数的返回值 文档化函数 函数传参数 文件操作(二) 1.文件操作的步骤 2.文件的内置方法 函数: 一.为什么要使用函数 在日常写代码中,我们会发现有很多 ...

  7. python成长之路第三篇(4)_作用域,递归,模块,内置模块(os,ConfigParser,hashlib),with文件操作

    打个广告欢迎加入linux,python资源分享群群号:478616847 目录: 1.作用域 2.递归 3.模块介绍 4.内置模块-OS 5.内置模块-ConfigParser 6.内置模块-has ...

  8. python成长之路——第三天

    一.collections系列: collections其实是python的标准库,也就是python的一个内置模块,因此使用之前导入一下collections模块即可,collections在pyt ...

  9. 我的Python成长之路---第五天---Python基础(17)---2016年1月30日(晴)

    常用模块 1.模块介绍 模块,用一砣代码实现了某个功能的代码集合. 模块分为三种 自定义模块 内置标准模块(又称标准库) 开源模块 2.常用模块 time模块 time.time() import t ...

随机推荐

  1. [转]关于 Swift 的一点初步看法

    本文转自:http://onevcat.com/2014/06/my-opinion-about-swift/ 感谢原作者 虽然四点半就起床去排队等入场,结果还是只能坐在了蛮后面的位置看着大屏幕参加了 ...

  2. Protel99SE制作拼板的方法

    制作步骤: 1.在PCB编辑里按快捷键 S/A全选复制源PCB全部内容,再按Ctrl+C看到十字光标.点击左键. 2.打开目标PCB文件,点击Edit菜单,在下拉菜单中点击Paste special( ...

  3. 用Mediawiki做百科网站资源大参考

    MediaWiki简易安装教程**关于mediawiki 一些好的资料: http://codex.wordpress.org.cn/Mediawiki%E5%BB%BA%E7%AB%99%E7%BB ...

  4. [转]chrome技术文档列表

    chrome窗口焦点管理系统 http://www.douban.com/note/32607279/ chrome之TabContents http://www.douban.com/note/32 ...

  5. Flex 按钮添加图标

    第一种是在Flex应用中创建一个变量,利用[Bindable]和[Embed] ,在代码中以参数形式传入制定图标(icon)的路径,然后利用类似icon="{Icon}"的代码嵌入 ...

  6. 九款让WordPress成为赚钱利器的广告插件

    Blog有了很不错的流量后,看到别人博客挂的广告挣$,是否也有挂广告的冲动,但是,修改wordpress模版去让人不厌其烦,布局.样式都的重新修改一下,为了不那么麻烦,笔者整理的几款wordpress ...

  7. Sightseeing Cows(最优比率环)

    Sightseeing Cows Time Limit: 1000MS   Memory Limit: 65536K Total Submissions: 8915   Accepted: 3000 ...

  8. java代码发送JSON格式的httpPOST请求

    package com.test; import java.io.BufferedReader; import java.io.DataOutputStream; import java.io.IOE ...

  9. Python lambda和reduce函数

    看到一篇博文写lambda和reduce函数.笔者小痒了一下,用Python实现一下: #! /usr/bin/env python # -*-coding:utf-8-*- import time ...

  10. c#简单的调试信息、日志信息输出

    public static void ErrorLog(string mssg) { string FilePath = "D:/logs/ErrorLog.txt"; try { ...