Python itertools 三种用法比较
·
1、 permutations 排列(有序,不重复选取)
import itertools x=['a','b','c'] perm=itertools.permutations(x) for i in perm: print(i)('a', 'b', 'c')
('a', 'c', 'b')
('b', 'a', 'c')
('b', 'c', 'a')
('c', 'a', 'b')
('c', 'b', 'a')
2、combinations 组合(无序,不重复选取)
import itertools x=['a','b','c'] prem=itertools.combinations(x,2) for i in prem: print(i)('a', 'b')
('a', 'c')
('b', 'c')
3、combinations_with_replacement 可重复组合
import itertools x=['a','b','c'] prem=itertools.combinations_with_replacement(x,2) for i in prem: print(i)('a', 'a')
('a', 'b')
('a', 'c')
('b', 'b')
('b', 'c')
('c', 'c')
4、product(允许重复选取,不传第二个参数时,默认次数1)
import itertools x=['a','b','c'] prem=itertools.product(x,repeat=2) for i in prem: print(i)('a', 'a')
('a', 'b')
('a', 'c')
('b', 'a')
('b', 'b')
('b', 'c')
('c', 'a')
('c', 'b')
('c', 'c')
更多推荐


所有评论(0)