# zip 案例
l1 =[1,2,3,4,5]
l2 =[11,22,33,44,55]z =zip(l1, l2)print(type(z))print(z)for i in z:print(i)help(zip)
<class 'zip'>
<zip object at 0x054A1BE8>
(1, 11)
(2, 22)
(3, 33)
(4, 44)
(5, 55)
Help on class zip in module builtins:class zip(object)| zip(iter1 [,iter2 [...]]) --> zip object| | Return a zip object whose .__next__() method returns a tuple where| the i-th element comes from the i-th iterable argument. The .__next__()| method continues until the shortest iterable in the argument sequence| is exhausted and then it raises StopIteration.| | Methods defined here:| | __getattribute__(self, name, /)| Return getattr(self, name).| | __iter__(self, /)| Implement iter(self).| | __next__(self, /)| Implement next(self).| | __reduce__(...)| Return state information for pickling.| | ----------------------------------------------------------------------| Static methods defined here:| | __new__(*args, **kwargs) from builtins.type| Create and return a new object. See help(type) for accurate signature.
l1 =["wangwang","mingyue","yyt"]
l2 =[89,23,78]z =zip(l1, l2)for i in z:print(i)# 考慮下面結果,為什么會為空
l3 =[i for i in z]print(l3)
('wangwang', 89)
('mingyue', 23)
('yyt', 78)
[]
enumerate
跟zip功能比較像
對可迭代對象里的每一元素,配上一個索引,然后索引和內容構成tuple類型
# enumerate案例1
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
deque
namedtuple
tuple類型
是一個可命名的tuple
import collections
Point = collections.namedtuple("Point",['x','y'])
p = Point(11,22)print(p.x)print(p[0])
11
11
Circle = collections.namedtuple("Circle",['x','y','r'])c = Circle(100,150,50)print(c)print(type(c))# 想檢測以下namedtuple到底屬于誰的子類isinstance(c,tuple)
Circle(x=100, y=150, r=50)
<class '__main__.Circle'>True