6.2. itertools模块中常用工具函数¶
6.2.1. 1.导入 itertools模块¶
import itertools
itertools模块中提供了近二十个迭代器工具函数,主要有三类,常用的主要有:
6.2.2. 2.无限迭代器:¶
count (start, [step]) # 从start开始,以step为步进行计数迭代
cycle (seq) # 无限循环迭代seq
repeat (elem, [n]) # 循环迭代elem
6.2.3. 3.迭代短序列:¶
chain (p, q, ...) #链接迭代(将p,q连接起来迭代,就像从一个序列中迭代)
compress (data, selectors) #依据selectors中的值选择迭代data序列中的值
dropwhile (pred, seq) #当pred对序列元素处理结果为假时开始迭代seq后所有值
filterfalse (pred, seq) #当pred处理为假的元素
takewhile (pred, seq) #与dropwhile相反
tee (it, n) #将it重复n次进行迭代
zip_longest (p,q,...)
6.2.4. 4.组合迭代序列¶
product (p, q,...[, n]) #迭代排列出所有的排列
permutations (p, r) #迭代序列中r个元素的排列
combinations (p, r) #迭代序列中r个元素的组合
4.1 代码示例¶
count (start, [step])
#!/usr/bin/env python
# -*- coding:utf8 -*-
# auther; 18793
# Date:2020/5/10 21:32
# filename: sample1.py
import itertools
for i in itertools.count(1, 3):
print(i)
if i >= 10:
break
"""
1
4
7
10
"""
cycle (seq)
import itertools
x = 0
for i in itertools.cycle(['a', 'b']):
print(i)
x += 1
if x > 6:
break
"""
a
b
a
b
a
b
a
"""
repeat (elem, [n])
import itertools
print(list(itertools.repeat(3, 3)))
#[3, 3, 3]
chain (p, q, ...)
print(list(itertools.chain([1, 3], [2, 3])))
#[1, 3, 2, 3]
compress (data, selectors)
print(list(itertools.compress([1, 2, 3, 4], [1, [], True, 3])))
dropwhile (pred, seq)
print(list(itertools.dropwhile(lambda x: x > 6, [8, 9, 1, 2, 8, 9])))
# [1, 2, 8, 9]
filterfalse (pred, seq)
print(list(itertools.takewhile(lambda x: x > 10, [18, 19, 1, 21, 8, 9])))
# [18, 19]
tee (it, n)
import itertools
for its in itertools.tee([0, 1], 2):
for it in its:
print(it)
'''
0
1
0
1
'''
permutations (p, r)
import itertools
print(list(itertools.permutations('abc', 2)))
# [('a', 'b'), ('a', 'c'), ('b', 'a'), ('b', 'c'), ('c', 'a'), ('c', 'b')]
combinations (p, r)
print(list(itertools.combinations('abc', 2)))
# [('a', 'b'), ('a', 'c'), ('b', 'c')]
使用无限迭代器时,必须有迭代退出的条件,否则会导致死循环。
4.2 itertools模块¶
#!/usr/bin/env python
# -*- coding:utf8 -*-
# auther; 18793
# Date:2019/6/17 14:00
# filename: itertools模块.py
import itertools
print([e for e in dir(itertools) if not e.startswith("_")])
import itertools as it
# 使用count(10,3)生成13、16、19....的迭代器
for e in it.count(10, 3):
print(e)
if e > 20:
break
print("---------------------")
my_counter = 0
# cycle用于对序列生成无限循环的迭代器
for e in it.cycle(["python", "kotlin", "Swift"]):
print(e)
# 用于跳出无限循环
my_counter += 1
if my_counter > 7:
break
print("--------------------------")
# repeat用于生成n个元素重复的迭代器
for e in it.repeat("python", 3):
print(e)
输出信息
['accumulate', 'chain', 'combinations', 'combinations_with_replacement', 'compress', 'count', 'cycle', 'dropwhile', 'filterfalse', 'groupby', 'islice', 'permutations', 'product', 'repeat', 'starmap', 'takewhile', 'tee', 'zip_longest']
10
---------------------
13
---------------------
16
---------------------
19
---------------------
22
python
kotlin
Swift
python
kotlin
Swift
python
kotlin
--------------------------
python
python
python