技术开发 频道

详解Python 3.1的新变化之标准程序库篇

  三、Itertools模块的改进

  Itertools模块不仅可以处理无穷序列,而且还可以处理有限序列。在Python 3.1中,它引入了两个新的函数:combinations_with_replacement()函数和compress()函数。

  函数combinations()能够按照词典顺序输出输入序列的子序列。新的combinations_with_replacement() 函数允许重复相同的要素,具体如下所示:

  from itertools import *

  
print(list(combinations([1, 2, 3, 4], 3)))

  
print('-' * 10)

  
print(list(combinations_with_replacement(['H', 'T'], 5)))

  输出的结果:

  [(1, 2, 3), (1, 2, 4), (1, 3, 4), (2, 3, 4)]

  
----------

  [(
'H', 'H', 'H', 'H', 'H'), ('H', 'H', 'H', 'H', 'T'),

  (
'H', 'H', 'H', 'T', 'T'), ('H', 'H', 'T', 'T', 'T'),

  (
'H', 'T', 'T', 'T', 'T'), ('T', 'T', 'T', 'T', 'T')]

  需要注意的是,这两个邯郸的每个子序列都是有序的。Compress()函数允许您对序列应用掩码以选择特定元素,该函数将在穷尽数列或者选择符掩码用尽时返回。下面的例子将使用compress()函数和count()函数来生成一个无穷的整数流,map()对count()的元素应用了一个lambda函数,最后chain()将两个iterables链在一起。最后生成的流与非负整数序列非常类似,不同之处是1出现了两次。 那么,compress()函数会从这个输入流中选择哪些内容呢?

  from itertools import *

  selectors
= [1, 1, 1, 1, 1, 0, 1, 0, 0, 1, 0, 0,

  0, 0,
1, 0, 0, 0, 0, 0, 0, 0, 1]

  sequence
= chain(iter([0, 1]), map(lambda x: x+1, count()))

  
print(list(compress(sequence, selectors)))

  输出的结果:

  [0, 1, 1, 2, 3, 5, 8, 13, 21]

0
相关文章