温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

python 内置模块collections

发布时间:2020-07-16 22:18:48 来源:网络 阅读:347 作者:ading2016 栏目:编程语言

1、namedtuple

from collections import namedtuple

websites = [
('Sohu', 'http://www.google.com/', u'张朝阳'),
('Sina', 'http://www.sina.com.cn/', u'王志东'),
('163', 'http://www.163.com/', u'丁磊')
]

Website = namedtuple('Website', ['name', 'url', 'founder'])
mywebsite = Website('ading', 'http://blog.65535.fun', u'林天来')
print(mywebsite.name)
print(mywebsite.url)
print(mywebsite.founder)
for website in websites:
website = Website._make(website)
print website

2、deque
In [1]: from collections import deque

In [2]: mydeque = deque(maxlen=10)

In [3]: mydeque.maxlen
Out[3]: 10

In [4]: mydeque.append(1)

In [5]: mydeque.append(10)

In [6]: mydeque
Out[6]: deque([1, 10])

In [7]: mydeque.appendleft('a')

In [8]: mydeque.appendleft('b')

In [9]: mydeque
Out[9]: deque(['b', 'a', 1, 10])

In [10]: mydeque.pop()
Out[10]: 10

In [11]: mydeque
Out[11]: deque(['b', 'a', 1])

In [12]: mydeque.popleft()
Out[12]: 'b'

In [13]: mydeque
Out[13]: deque(['a', 1])

deque 还有常用的方法 :copy,reverse, insert, clear

3、OrderedDict
使用dict时,在遍历字典时是无法指定key的顺序的,但OrderedDict 是可以的

In [1]: from collections import OrderedDict

In [2]: od = OrderedDict

In [3]: od = OrderedDict()

In [4]: od['aa'] = 11

In [5]: od['bb'] = 22

In [6]: od['cc'] = 33

In [7]: od
Out[7]: OrderedDict([('aa', 11), ('bb', 22), ('cc', 33)])

4、defaultdict
默认值是在调用difaultdict 时传入一个可调用函数。
In [1]: from collections import defaultdict

In [2]: df = defaultdict(lambda: 'aa')

In [3]: df['key1'] = 11

In [4]: df['key2']
Out[4]: 'aa'

In [5]: df
Out[5]: defaultdict(<function main.<lambda>()>, {'key1': 11, 'key2': 'aa'})

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI