擅长:python、mysql、java
<p><a href="https://docs.python.org/3/library/itertools.html#itertools.product" rel="nofollow">^{<cd1>}</a>已经可以准确地完成您想要的任务,只需将多个iterable(在本例中是您想要的范围)传递给它即可。它将从每个传递的iterable中收集一个元素。例如:</p>
<pre><code>for a,b,c in product(range(2), range(3), range(4)):
print (a,b,c)
</code></pre>
<p><strong>输出</strong>:</p>
<pre><code>0 0 0
0 0 1
0 0 2
0 0 3
0 1 0
0 1 1
0 1 2
0 1 3
0 2 0
0 2 1
0 2 2
0 2 3
1 0 0
1 0 1
1 0 2
1 0 3
1 1 0
1 1 1
1 1 2
1 1 3
1 2 0
1 2 1
1 2 2
1 2 3
</code></pre>
<p>如果您的输入范围是可变的,只需将循环放在函数中并用不同的参数调用它。你也可以按照</p>
<pre><code>for elements in product(*(range(i) for i in [1,2,3,4])):
print(*elements)
</code></pre>
<p>如果您有大量的输入iterables。你知道吗</p>
<hr/>
<p>对于变量范围的更新请求,<code>itertools.product</code>的一种很好的短路方法并不那么清楚,尽管您总是可以检查每个iterable是否按升序排序(因为变量范围基本上就是这样确保的)。根据你的例子:</p>
<pre><code>for elements in product(*(range(i) for i in [10,10,10,10])):
if all(elements[i] <= elements[i+1] for i in range(len(elements)-1)):
print(*elements)
</code></pre>