[python] itertools库学习

最近做 cyber-dojo上的题,好几道都要用到排列组合。一开始我还老老实实自己写算法。后来一想,不对呀!python有那么多的库,为啥不用呢?

于是搜了下,发现这个:itertools

使用 help(itertools)可以查看帮助,不过内容多了容易头痛,我们慢慢来先。

用dir看个大概:

>>> dir(itertools)
['__doc__', '__file__', '__name__', '__package__', 'chain', 'combinations', 'combinations_with_replacement', 'compress', 'count', 'cycle', 'dropwhile', 'groupby', 
'ifilter', 'ifilterfalse', 'imap', 'islice', 'izip', 'izip_longest', 'permutations', 'product', 'repeat', 'starmap', 'takewhile', 'tee']

 ------------------------------默默地查下单词先--------------------------------------

combinations 英 [ kɒmbɪ'neɪʃnz ] 美 [ kɒmbɪ'neɪʃnz ]   n.合作( combination的名词复数 ); 密码组合; 联合体; 排列

permutations 英 [ pɜ:mju:'teɪʃnz ] 美 [ pɜmju'teɪʃnz ] n. (一组事物可能的一种)序列,排列,排列中的任一组数字或文字( permutation的名词复数 )

cartesian 英 [ kɑ:ˈti:ziən ] 美 [ kɑrˈtiziən ] adj. 笛卡尔的,笛卡尔哲学的 n. 笛卡尔信徒

>>> def pr(a):
...   for e in a:
...     print e
  • combinations
>>> s = ['A', 'T', 'C', 'G']
>>> com = itertools.combinations(s,1)
>>> pr(com)
('A',)
('T',)
('C',)
('G',)
>>> com = itertools.combinations(s,2)
>>> pr(com)
('A', 'T')
('A', 'C')
('A', 'G')
('T', 'C')
('T', 'G')
('C', 'G')
>>> com = itertools.combinations(s,3)
>>> pr(com)
('A', 'T', 'C')
('A', 'T', 'G')
('A', 'C', 'G')
('T', 'C', 'G')
>>> com = itertools.combinations(s,4)
>>> pr(com)
('A', 'T', 'C', 'G')
  •  permutations
>>> per = itertools.permutations(s)
>>> pr(per)
('A', 'T', 'C', 'G')
('A', 'T', 'G', 'C')
('A', 'C', 'T', 'G')
('A', 'C', 'G', 'T')
('A', 'G', 'T', 'C')
('A', 'G', 'C', 'T')
('T', 'A', 'C', 'G')
('T', 'A', 'G', 'C')
('T', 'C', 'A', 'G')
('T', 'C', 'G', 'A')
('T', 'G', 'A', 'C')
('T', 'G', 'C', 'A')
('C', 'A', 'T', 'G')
('C', 'A', 'G', 'T')
('C', 'T', 'A', 'G')
('C', 'T', 'G', 'A')
('C', 'G', 'A', 'T')
('C', 'G', 'T', 'A')
('G', 'A', 'T', 'C')
('G', 'A', 'C', 'T')
('G', 'T', 'A', 'C')
('G', 'T', 'C', 'A')
('G', 'C', 'A', 'T')
('G', 'C', 'T', 'A')
>>> per1 = itertools.permutations(s,1)
>>> pr(per1)
('A',)
('T',)
('C',)
('G',)
>>> per2 = itertools.permutations(s,2)
>>> pr(per2)
('A', 'T')
('A', 'C')
('A', 'G')
('T', 'A')
('T', 'C')
('T', 'G')
('C', 'A')
('C', 'T')
('C', 'G')
('G', 'A')
('G', 'T')
('G', 'C')
>>> per3 = itertools.permutations(s,3)
>>> pr(per3)
('A', 'T', 'C')
('A', 'T', 'G')
('A', 'C', 'T')
('A', 'C', 'G')
('A', 'G', 'T')
('A', 'G', 'C')
('T', 'A', 'C')
('T', 'A', 'G')
('T', 'C', 'A')
('T', 'C', 'G')
('T', 'G', 'A')
('T', 'G', 'C')
('C', 'A', 'T')
('C', 'A', 'G')
('C', 'T', 'A')
('C', 'T', 'G')
('C', 'G', 'A')
('C', 'G', 'T')
('G', 'A', 'T')
('G', 'A', 'C')
('G', 'T', 'A')
('G', 'T', 'C')
('G', 'C', 'A')
('G', 'C', 'T')
原文地址:https://www.cnblogs.com/Clisa/p/5626794.html