Home > Backend Development > Python Tutorial > python 排列组合之itertools

python 排列组合之itertools

WBOY
Release: 2016-06-06 11:27:57
Original
1427 people have browsed it

python 2.6 引入了itertools模块,使得排列组合的实现非常简单:

代码如下:


import itertools 


有序排列:e.g., 4个数内选2个排列:

代码如下:


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


无序组合:e.g.,4个数内选2个:

代码如下:


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

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template