有用的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()