您的位置:首页 > 编程语言 > Python开发

python的几种有用的函数 itertools库

2017-01-22 00:00 204 查看
import itertools

b = [('a', -1), ('b', 'b1'), ('c', 'cs')]

#笛卡尔积
list(itertools.product(*b))

[('a', 'b', 'c'),
('a', 'b', 'cs'),
('a', 'b1', 'c'),
('a', 'b1', 'cs'),
(-1, 'b', 'c'),
(-1, 'b', 'cs'),
(-1, 'b1', 'c'),
(-1, 'b1', 'cs')]

#排列
list(itertools.permutations(b, 2))

[(('a', -1), ('b', 'b1')),
(('a', -1), ('c', 'cs')),
(('b', 'b1'), ('a', -1)),
(('b', 'b1'), ('c', 'cs')),
(('c', 'cs'), ('a', -1)),
(('c', 'cs'), ('b', 'b1'))]

#组合,没有重复
list(itertools.combinations(b, 2))
[(('a', -1), ('b', 'b1')),
(('a', -1), ('c', 'cs')),
(('b', 'b1'), ('c', 'cs'))]

#组合,有重复
list(itertools.combinations_with_replacement(b, 2))

[(('a', -1), ('a', -1)),
(('a', -1), ('b', 'b1')),
(('a', -1), ('c', 'cs')),
(('b', 'b1'), ('b', 'b1')),
(('b', 'b1'), ('c', 'cs')),
(('c', 'cs'), ('c', 'cs'))]
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: