itertools
Python的内建模块itertools提供了非常有用的用于操作迭代对象的函数。
无限迭代器
itertools.count 不停打印自然数
示例代码
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Python基础 itertools
import itertools
# 无限迭代器
natuals = itertools.count(1)
for n in natuals:
# 不停打印自然数
print(n)
运行结果
D:\PythonProject>python main.py
1
2
3
4
5
6
7
无限打印
itertools.cycle 不停循环打印
运行示例
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Python基础 itertools
import itertools
# 无限迭代器
cs = itertools.cycle("xyz")
for c in cs:
print(c)
运行结果
.............
x
y
z
x
y
z
x
y
...........
itertools.repeat 限定重复次数
运行示例
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Python基础 itertools
import itertools
# repeat 限定重复次数
# 将good 重复3次打印
cs = itertools.repeat("good", 3)
for c in cs:
print(c)
运行结果
D:\PythonProject>python main.py
good
good
good
itertools.takewhile让无限变成有限序列
示例代码
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Python基础 itertools
import itertools
# takewhile让无限变成有限序列
natuals = itertools.count(1)
n = itertools.takewhile(lambda x:x<=10, natuals)
ns = list(n)
print(ns)
运行结果
D:\PythonProject>python main.py
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
chain 大迭代器 = 迭代器A + 迭代器 B
运行示例
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Python基础 itertools
import itertools
# chain 大迭代器 = 迭代器A + 迭代器 B
big = itertools.chain("ABC","XYZ")
for c in big:
print(c)
运行结果
D:\PythonProject>python main.py
A
B
C
X
Y
Z
groupby挑出重复并分组
运行示例
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Python基础 groupby
import itertools
# groupby挑出重复并分组
data = "AAACCCCDDDDD"
groupList = itertools.groupby(data)
for key, group in groupList:
print(key, list(group))
运行结果
D:\PythonProject>python main.py
A ['A', 'A', 'A']
C ['C', 'C', 'C', 'C']
D ['D', 'D', 'D', 'D', 'D']