文件名称:排列组合的迭代-python cookbook(第3版)高清中文完整版
文件大小:4.84MB
文件格式:PDF
更新时间:2024-06-29 23:06:04
python cookbook 第3版 高清 中文完整版
4.9 排列组合的迭代 问题 你想迭代遍历一个集合中元素的所有可能的排列或组合 解决方案 itertools模块提供了三个函数来解决这类问题。 其中一个是 itertools.permutations() , 它接受一个集合并产生一个元组序列,每个元组由集合中所有元素的一个可能排列组成。 也就是说通过打乱集合中元素排列顺序生成一个元组,比如: >>> items = ['a', 'b', 'c'] >>> from itertools import permutations >>> for p in permutations(items): ... print(p) ... ('a', 'b', 'c') ('a', 'c', 'b') ('b', 'a', 'c') ('b', 'c', 'a') ('c', 'a', 'b') ('c', 'b', 'a') >>> 如果你想得到指定长度的所有排列,你可以传递一个可选的长度参数。就像这样: >>> for p in permutations(items, 2): ... print(p) ... ('a', 'b') ('a', 'c') ('b', 'a') ('b', 'c') ('c', 'a') ('c', 'b') >>>