zip
- 把两个可迭代内容生成一个可迭代的tuple元素类型组成的内容
# zip案例
l1 = [1, 2, 3, 4, 5]
l2 = [11, 22, 33, 44, 55, 66]
z = zip(l1, l2)
print(type(z))
ls = [i for i in z]
print(ls)
<class 'zip'>
[(1, 11), (2, 22), (3, 33), (4, 44), (5, 55)]
enumerate
- 跟zip功能比较像
- 对可迭代对象里的每一元素,配上一索引,然后索引和内容构成tuple类型
l1 = [11, 22, 33, 44, 55]
em = enumerate(l1)
print(type(em))
l2 = [i for i in em]
print(l2)
<class 'enumerate'>
[(0, 11), (1, 22), (2, 33), (3, 44), (4, 55)]
collections模块
import collections
Point = collections.namedtuple("Point", ['x', 'y'])
p = Point(11, 22)
print(type(Point))
print(type(p))
# 检测以下namedtuple到底属于谁的子类
t = isinstance(p, tuple)
print(t)
print(p.x)
print(p[0])
<class 'type'>
<class '__main__.Point'>
True
11
11
Circle = collections.namedtuple("Circle", ['x', 'y', 'r'])
c = Circle(100, 150, 50)
print(c)
Circle(x=100, y=150, r=50)
网友评论