zip
-把两个可迭代内容生成一个可迭代的tuple元素类型组成的内容
#zip案例
l1=[1,2,3,4,5,6,7,8]
l2=[11,22,33,44,55,66,77,88]
z=zip(l1,l2)
for i in z:
print(i)
(1, 11)
(2, 22)
(3, 33)
(4, 44)
(5, 55)
(6, 66)
(7, 77)
(8, 88)
enumerate
-跟zip功能相近
-对可迭代对象的每一个元素,加上一个索引,然后索引和内容构成tuple类型
#enumerate案例1
l1=[11,22,33,44,55,66,77,88]
em=enumerate(l1)
l2=[i for i in em]
print(l2)
[(0, 11), (1, 22), (2, 33), (3, 44), (4, 55), (5, 66), (6, 77), (7, 88)]
#enumerate案例2
em=enumerate(l1,start=100)
collections模块
-namedtuple
-dequeue
#namedtuple
-tuple类型,是一个可命名的tuple
import collections
Point=collections.namedtuple('Point',['x','y'])
p=Point(22,44)
print(p.x)
print(p[0])
22
22
dequeue
-方便的解决了删除插入带来的效率的问题
from collections import deque
p=deque(['a','b','c',])
print(p)
p.append('d')
print(p)
p.appendleft('z')
print(p)
deque([‘a’, ‘b’, ‘c’])
deque([‘a’, ‘b’, ‘c’, ‘d’])
deque([‘z’, ‘a’, ‘b’, ‘c’, ‘d’])
defaultdict
-当读取dict不存在的属性是,直接返回默认值
from collections import defaultdict
d={'one':1,'two':2,'three':3}
func=lambda:'None'
d=defaultdict(func)
print(d['four'])
one
None
Counter
-统计字符串的个数
from collections import Counter
l="abbbbasbbbbdbbfbbbtbbybhbybybb6bbyb"
c=Counter(l)
print(c)
Counter({‘b’: 23, ‘y’: 4, ‘a’: 2, ‘s’: 1, ‘d’: 1, ‘f’: 1, ‘t’: 1, ‘h’: 1, ‘6’: 1})