collections --容器数据类型,collections模块包含了除内置类型list,dict和tuple以外的其他容器数据类型。

Counter 作为一个容器可以追踪相同的值增加了多少次

#初始化
print(collections.Counter('qweqwe'))
print(collections.Counter(['q','w','e','q','w','e']))
print(collections.Counter(q=2,w=2,e=2,))
print(collections.Counter({'q':2,'w':2,'e':2})) 结果:
Counter({'q': 2, 'e': 2, 'w': 2})
Counter({'q': 2, 'e': 2, 'w': 2})
Counter({'q': 2, 'e': 2, 'w': 2})
Counter({'q': 2, 'e': 2, 'w': 2})
#构造空的Counter,使用update()填充
c = collections.Counter()
print(c)
c.update('qweqwe')
print(c)
c.update(['q','e','w','w'])
c.update({'q':2,'e':2})#计数值会增加,替换数据不会改变计数
c.update('qqew')
print(c) 结果:
Counter()
Counter({'w': 2, 'e': 2, 'q': 2})
Counter({'q': 7, 'e': 6, 'w': 5})
# 访问计数,一旦填充了Counter,可以使用 字典api获取他的值
b = collections.Counter('qwedwewqsa')
for letter in 'qwedz':
print('%s:%d'%(letter,b[letter]),end=',') b['x']=0
print(b)
print(list(b.elements()))#elements()返回一个迭代器,将生成Counter中的所有元素,但是不包括计数小于或者等于0的元素 string1 = '这是一段测试文文文字,这用来测试数据数数数结构常常判断数据是否可以正常使用,常用的正常的测试文章结果结构构造'
s = collections.Counter(string1)
for letter,count in s.most_common(3): #most_common()生成一个序列,其中包含n个最常遇到的输入值和相应的计数
print('%s:%d'%(letter,count),end='|') 结果:
q:2,w:3,e:2,d:1,z:0,Counter({'w': 3, 'q': 2, 'e': 2, 's': 1, 'a': 1, 'd': 1, 'x': 0})
['q', 'q', 's', 'e', 'e', 'w', 'w', 'w', 'a', 'd']
数:5|常:5|文:4|
#算术操作
c1 = collections.Counter('qqqwwweeedx')
c2 = collections.Counter(['q','q','w','w','e','e','d','v'])
print(c1-c2)#每次通过一次操作生成新的Counter时候,计数为0或者负数会被删除
print(c1+c2)
print(c1&c2)
print(c1|c2) 结果:
Counter({'x': 1, 'w': 1, 'e': 1, 'q': 1})
Counter({'e': 5, 'w': 5, 'q': 5, 'd': 2, 'x': 1, 'v': 1})
Counter({'w': 2, 'e': 2, 'q': 2, 'd': 1})
Counter({'e': 3, 'w': 3, 'q': 3, 'x': 1, 'd': 1, 'v': 1})

 defaultdict 初始化容器时候会先让调用者提前指定默认值

def default_factory():
return 'default value' d = collections.defaultdict(default_factory,foo='bar')
print(d)
print(d['foo'],d['bar'],d['par']) 结果:
defaultdict(<function default_factory at 0x00000233EF0B7F28>, {'foo': 'bar'})
bar default value default value

deque(双端队列),支持从任意一端增加和删除元素,更为常见的两种结构,栈与队列,就是双端队列的退化形式,其输入和输出限制在一端

d = collections.deque('asdzxc')
print(d,len(d),('left end:',d[0]),('right end',d[-1]))
d.remove('d')
print('remove(d):',d)#deque属于序列容器,支持list的一些操作 结果:
deque(['a', 's', 'd', 'z', 'x', 'c']) 6 ('left end:', 'a') ('right end', 'c')
remove(d): deque(['a', 's', 'z', 'x', 'c'])
# 填充
d1 = collections.deque()
d1.extend('abcdefg')#迭代处理其输入
print('extend:',d1)
d1.append('hijk')
print('append',d1)
d1.extendleft('lmn')
print('extendleft:',d1)
d1.appendleft('opq')
print('appendleft',d1) 结果:
extend: deque(['a', 'b', 'c', 'd', 'e', 'f', 'g'])
append deque(['a', 'b', 'c', 'd', 'e', 'f', 'g', 'hijk'])
extendleft: deque(['n', 'm', 'l', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'hijk'])
appendleft deque(['opq', 'n', 'm', 'l', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'hijk'])
#使用,可以从任意一端取deque的元素
print('from right')
d = collections.deque('abcdefg')
while True:
try:
print(d.pop(),end=',')
except IndexError:
break
print()
print('from left')
n = collections.deque(range(6))
while True:
try:
print(n.popleft(),end=',')
except IndexError:
break 结果:
from right
g,f,e,d,c,b,a,
from left
0,1,2,3,4,5,
#使用不同线程同时从两端利用双端队列的内容
import threading
import time
candle = collections.deque(range(5))
def burn(direction,nextSource):
while True:
try:
next=nextSource()
except IndexError:
break
else:
print('%8s:%s'%(direction,next))
time.sleep(1) print('%8s done'%direction)
return left = threading.Thread(target=burn,args=('left',candle.popleft))
right = threading.Thread(target=burn,args=('right',candle.pop)) left.start()
right.start() left.join()
right.join() 结果:
left:0
right:4
right:3
left:1
left:2
right done
left done
#旋转,按照任意一个方向旋转,跳过一些元素
d = collections.deque(range(10))
print(d)
d.rotate(2)#使用正值,会从右端取数据移动到左端
print(d)
d.rotate(-4)#使用负值,会从左端取数据移动到右端
print(d) 结果:
deque([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
deque([8, 9, 0, 1, 2, 3, 4, 5, 6, 7])
deque([2, 3, 4, 5, 6, 7, 8, 9, 0, 1])

 OrderedDict是一个字典的子类,可以记住其内容增加的顺序,是有序的


d = collections.OrderedDict()
d['a'] = 1
d['b'] = 2
d['c'] = 3 for k,v in d.items():
print(k,v) d1 = collections.OrderedDict()
d1['a'] = 1
d1['b'] = 2
d1['c'] = 3 d2 = collections.OrderedDict()
d2['b'] = 2
d2['a'] = 1
d2['c'] = 3 print(d1==d2)
结果: 

a 1
b 2
c 3
False

python数据结构(一)的更多相关文章

  1. python数据结构与算法

    最近忙着准备各种笔试的东西,主要看什么数据结构啊,算法啦,balahbalah啊,以前一直就没看过这些,就挑了本简单的<啊哈算法>入门,不过里面的数据结构和算法都是用C语言写的,而自己对p ...

  2. python数据结构与算法——链表

    具体的数据结构可以参考下面的这两篇博客: python 数据结构之单链表的实现: http://www.cnblogs.com/yupeng/p/3413763.html python 数据结构之双向 ...

  3. python数据结构之图的实现

    python数据结构之图的实现,官方有一篇文章介绍,http://www.python.org/doc/essays/graphs.html 下面简要的介绍下: 比如有这么一张图: A -> B ...

  4. Python数据结构与算法--List和Dictionaries

    Lists 当实现 list 的数据结构的时候Python 的设计者有很多的选择. 每一个选择都有可能影响着 list 操作执行的快慢. 当然他们也试图优化一些不常见的操作. 但是当权衡的时候,它们还 ...

  5. Python数据结构与算法--算法分析

    在计算机科学中,算法分析(Analysis of algorithm)是分析执行一个给定算法需要消耗的计算资源数量(例如计算时间,存储器使用等)的过程.算法的效率或复杂度在理论上表示为一个函数.其定义 ...

  6. Python数据结构与循环语句

    # Python数据结构与循环语句:   首先编程是一项技能,类似跑步,期初不必在意细节,能使用起来就行,等学的游刃有余了再回过头来关注细节问题也不迟.  关于买书: 学会python之后,才需要买书 ...

  7. python数据结构之栈与队列

    python数据结构之栈与队列 用list实现堆栈stack 堆栈:后进先出 如何进?用append 如何出?用pop() >>> >>> stack = [3, ...

  8. python数据结构之树和二叉树(先序遍历、中序遍历和后序遍历)

    python数据结构之树和二叉树(先序遍历.中序遍历和后序遍历) 树 树是\(n\)(\(n\ge 0\))个结点的有限集.在任意一棵非空树中,有且只有一个根结点. 二叉树是有限个元素的集合,该集合或 ...

  9. Python数据结构之四——set(集合)

    Python版本:3.6.2  操作系统:Windows  作者:SmallWZQ 经过几天的回顾和学习,我终于把Python 3.x中的基础知识介绍好啦.下面将要继续什么呢?让我想想先~~~嗯,还是 ...

  10. Python数据结构之单链表

    Python数据结构之单链表 单链表有后继结点,无前继结点. 以下实现: 创建单链表 打印单链表 获取单链表的长度 判断单链表是否为空 在单链表后插入数据 获取单链表指定位置的数据 获取单链表指定元素 ...

随机推荐

  1. Java实现 蓝桥杯VIP 算法训练 友好数

    有两个整数,如果每个整数的约数和(除了它本身以外)等于对方,我们就称这对数是友好的.例如: 9的约数和有:1+3=4 4的约数和有:1+2=3 所以9和4不是友好的. 220的约数和有:1 2 4 5 ...

  2. java实现串中找数字

    串中找数字 以下的静态方法实现了:把串s中第一个出现的数字的值返回. 如果找不到数字,返回-1 例如: s = "abc24us43" 则返回2 s = "82445ad ...

  3. org.openqa.selenium.WebDriverException: It is impossible to create a new session because 'createSession' which takes HttpClient, InputStream and long was not found or it is not accessible 异常

    检查项目配置的jdk版本是否过低,修改一下配置就解决了.如果是jdk版本过低的就升级一下jdk.

  4. [TopCoder]Seatfriends

    题目   点这里看题目. 分析   可以想到用 DP 解决.   由于把空位放到状态里面太麻烦了,因此我们单独将 " 组 " 提出来进行 DP .   \(f(i,j)\):前\( ...

  5. centos7 hadoop 单机模式安装配置

    前言 由于现在要用spark,而学习spark会和hdfs和hive打交道,之前在公司服务器配的分布式集群,离开公司之后,自己就不能用了,后来用ambari搭的三台虚拟机的集群太卡了,所以就上网查了一 ...

  6. 软件包,API,SDK的区别

    参考资料: https://www.jianshu.com/p/cac186cb168b https://blog.csdn.net/snowin1994/article/details/806080 ...

  7. Mac下安装octave

    1.首先安装Command Line Tool xcode-select --install2.Mac OSX平台下,用神器Homebrew安装 curl -LsSf http://github.co ...

  8. pikachu 搭建

    一:首先下载XAMPP 1.先到官方网站安装XAMPP  https://www.apachefriends.org/zh_cn/index.html 选择适合自己的电脑系统下载,本次windows系 ...

  9. cb07a_c++_迭代器和迭代器的范围

    cb07a_c++_迭代器和迭代器的范围c++primer第4版https://www.cnblogs.com/txwtech/p/12309989.html--每一种容器都有自己的迭代器--所有的迭 ...

  10. Day7-微信小程序实战-天气预报小程序

    前段时间在B站跟着一个视频,搞天气预报小程序 https://www.bilibili.com/video/BV1cJ411879s 但是因为这个调用的接口要money,太贵了就没买,就只是做了一些不 ...