1. zip
将两个可迭代内容合成一个tuple类型元素组成的可迭代内容
l1 = ["a", "b", "c", "d", "e"]
l2 = [1, 2, 3, 4, 5]
z = zip(l1, l2)
for i in z:
print(i)
结果如下:
('a', 1)
('b', 2)
('c', 3)
('d', 4)
('e', 5)
2. enumerate 枚举
将列表元素加上索引,生成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)]
- 修改索引的起始点
l1 = [11, 22, 33, 44, 55]
em = enumerate(l1, start = 100)
l2 = [i for i in em]
print(l2)
结果如下:
[(100, 11), (101, 22), (102, 33), (103, 44), (104, 55)]
3. namedtuple
- 生成可以使用名字来访问元素内容的tuple子类
- 需要加载collections模块
import collections
Point = collections.namedtuple("Point", ["x", "y"])
p = Point(11, 22)
print(p)
print(p.x)
print(p[1])
结果
Point(x=11, y=22)
11
22
Circle = collections.namedtuple("Circle", ["x", "y", "r"])
c = Circle(100, 150, 50)
print(c)
print(isinstance(c, tuple))
结果为
Circle(x=100, y=150, r=50)
True
4. deque
- 比较方便的解决了频繁删除插入带来的效率问题
- 需要加载collections模块
from collections import deque
q = deque(["a", "b", "c", "d"])
q.append("e")
print(q)
q.appendleft("x")
print(q)
结果如下
deque(['a', 'b', 'c', 'd', 'e'])
deque(['x', 'a', 'b', 'c', 'd', 'e'])
5. defaultdict
- 当直接读取dict不存在的属性时,直接返回默认值
- 需要加载collections模块
- defaultdict(function)
from collections import defaultdict
func = lambda: "没有找到"
d2 = defaultdict(func)
d2["one"] = 1
d2["two"] = 2
print(d2["two"])
print(d2["six"])
- Counter
- 统计字符串个数
- 需要加载collections模块
from collections import Counter
c1 = Counter("abdcadcdabcccabc")
print(c1)
c2 = Counter(["Beijing", "Tianjin", "Shenzhen", "Beijing"])
print(c2)
结果如下
Counter({'c': 6, 'a': 4, 'b': 3, 'd': 3})
Counter({'Beijing': 2, 'Tianjin': 1, 'Shenzhen': 1})