l1 =[1,2,3,4,5]
l2 =[11,22,33,44,55]
z =zip(l1,l2)for i in z:print(i)>>>(1,11)(2,22)(3,33)(4,44)(5,55)
enumerate
跟zip功能比较像
对可迭代对象里的每一元素,配上一个索引,然后索引和内容构成tuple类型
l1 =[11,22,33,44,55]
em =enumerate(l1)
l2 =[i for i in em]print(l2)>>>[(0,11),(1,22),(2,33),(3,44),(4,55)]----
em =enumerate(l1, start =100)
l2 =[i for i in em]print(l2)>>>[(100,11),(101,22),(102,33),(103,44),(104,55)]
collections模块
namedtuple
是一个可命名的tuple
deque
比较方便的解决了频繁的删除插入带来的问题
import collections
Point = collections.namedtuple("Point",['x','y'])
p = Point(11,22)print(p.x)print(p[0])>>>1111-----
Circle = collections.namedtuple("Circle",['x','y','r'])
c = Circle(100,150,50)print(c)>>>
Circle(x=100, y=150, r=50)
from collections import defaultdict
func =lambda:"dana"
d2 = defaultdict(func)
d2["one"]=1
d2["two"]=2print(d2['one'])print(d2['four'])>>>1
dana
Counter
统计字符串个数
from collections import Counter
c = Counter("afgdafgjhdsfha")# 括号中要放入可迭代的东西print(c)>>>
Counter({'a':3,'f':3,'g':2,'d':2,'h':2,'j':1,'s':1})----
s =["dana","haha","dana","hehe","xixi","hehe"]
c = Counter(s)print(c)>>>>
Counter({'dana':2,'hehe':2,'haha':1,'xixi':1})