Python 的 itertools 模块

Python 当中的 itertools 模块的存在感一直不高,可能是大家真正用到的时候并不多。然而,最近它却成功引起了我的注意,它在时大放异彩,所以,不妨再来学一学,不求别的,只求在解决问题的过程当中至少能成功想到它一次。

itertools.combinations

求列表的 k 阶子列

import itertools
 
input_list = [1, 2, 4, 3, 5]
n = len(input_list)
k = 3
for i in range(1, n + 1):
    i_subsequence = itertools.combinations(input_list, i)
    if i == k:
        k_subsequence = list(i_subsequence)
        print(k_subsequence)
[(1, 2, 4), (1, 2, 3), (1, 2, 5), (1, 4, 3), (1, 4, 5), (1, 3, 5), (2, 4, 3), (2, 4, 5), (2, 3, 5), (4, 3, 5)]

 itertools.count

创建一个自定义步长的无限迭代器 —— 不主动 break 的话,停不下来。(这块感觉和 range 的功能差不多,只不过一般用 range 的时候都是生成一个有限的迭代器)

import itertools

start = 2
step = 3
end = 11
for i in itertools.count(start, step):
    print(i)
    if i == end:
        break
start = 2
step = 3
end = 11

for i in range(start, end + 1, step):
    print(i)
2
5
8
11

上一篇:itertools 中的 permutations 实现全排列和任意排列


下一篇:Python函数式编程