Python3 集合collections与itertools介绍outline

有用的collections及内建函数

enumerate函数
对一个列表或数组既要遍历索引又要遍历元素时

case 1 for索引方式
l = [1,2,3,4]
for i in range(len(l)):
    print(i, l[i])

enumerate方法
enumerate会将数组或列表组成一个索引序列。使再次获取索引和索引内容的时候更加方便
for index, text in enumerate(l):
    print(index, text)

集合模块collections

是Python内建的一个集合模块,提供许多有用的集合类

deque高效实现插入、删除操作的双向列表,适合于队列和栈
OrderDict的Key会按照插入的顺序排列
Counter是一个简单的计数器,也是dict的一个子类

from collections import namedtuple
from collections import deque
from collections import defaultdict
from collections import OrderedDict
from collections import Counter

Point = namedtuple('Point', ['x', 'y'])
p = Point(1,2)

q = deque(['a','b', 'c'])
q.append('x')
q.appendleft('y')

dd = defaultdict(lambda:'N/A')
dd['key1'] = 'abc'

c = Counter()
for ch in 'programming':
    c[ch] = c[ch] + 1
print(c)

迭代器itertools

为类序列对象提供了一个类序列接口

无限迭代器
Iterator    Arguments               Results                             Example
count()     start,[step]        start, start+step, start+2*step,...     count(10)  -> 10 11 12 13 14 ...
cycle()     p                   p0,p1,...plast,p0,p1,..                 cycle('ABCD') --> A B C D A B C D
repeat()    elem[,n]            elem,elem,elem,...                     repeat(10,3) --> 10 10 10

在最短输入序列终止的迭代器:

chain()
compress()
dropwhile()
groupby()
ifilter()
ifilterfalse()
islice()
imap()
startmap()
tee()
takewhile()
izip()
izip_longest()
product()
permutations()
combinations()
combinations_with_replacement()

参考:

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值