欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

python 排列组合

程序员文章站 2022-07-14 09:39:44
...
# 导入模块
import itertools

# 组合(combinations)

参数:

组合(iterable,r)——>组合对象

返回迭代中元素的连续的r -长度组合。
组合(范围(4),3)- >(0,1,2)(0,1,3),(0、2、3),(1、2、3)

:print(list(itertools.combinations([1,2,3],3)))  

# 排列(permutations)

参数:

排列(iterable[,r])——>置换对象
返回迭代中元素的连续r -长度排列。
排列(范围(3),2)——>(0,1),(0,2),(1,0)、(1、2),(2,0),(2,1)

:print(list(itertools.permutations([1,2,3],2))) 

# 重复(product)





# 导入模块
import itertools
# 组合
print(list(itertools.combinations([1,2,3],2)))
输出:[(1, 2), (1, 3), (2, 3)]
print(list(itertools.combinations([1,2,3],3)))
输出:[(1, 2, 3)]
# 排列
print(list(itertools.permutations([1,2,3],2)))
输出[(1, 2), (1, 3), (2, 1), (2, 3), (3, 1), (3, 2)]
print(list(itertools.permutations([1,2,3],3)))
输出[(1, 2, 3), (1, 3, 2), (2, 1, 3), (2, 3, 1), (3, 1, 2), (3, 2, 1)]
# 重复排列
print([''.join(x) for x in itertools.product('12', repeat=2)])
输出:['11', '12', '21', '22']
print([''.join(x) for x in itertools.product('12', repeat=3)])
输出:['111', '112', '121', '122', '211', '212', '221', '222']