擅长:python、mysql、java
<p><em>以下仅适用于Python2.6及更高版本的代码</em></p>
<p>首先,导入<code>itertools</code>:</p>
<pre><code>import itertools
</code></pre>
<h3>排列(顺序问题):</h3>
<pre><code>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)]
</code></pre>
<h3>组合(顺序无关紧要):</h3>
<pre><code>print list(itertools.combinations('123', 2))
[('1', '2'), ('1', '3'), ('2', '3')]
</code></pre>
<h3>笛卡尔积(带若干个iterable):</h3>
<pre><code>print list(itertools.product([1,2,3], [4,5,6]))
[(1, 4), (1, 5), (1, 6),
(2, 4), (2, 5), (2, 6),
(3, 4), (3, 5), (3, 6)]
</code></pre>
<h3>笛卡尔积(有一个iterable和它本身):</h3>
<pre><code>print list(itertools.product([1,2], repeat=3))
[(1, 1, 1), (1, 1, 2), (1, 2, 1), (1, 2, 2),
(2, 1, 1), (2, 1, 2), (2, 2, 1), (2, 2, 2)]
</code></pre>