<p>三种可能的方法:</p>
<ol>
<li><p>可读性</p>
<pre><code>new_list = []
for a in list1:
for b in list2:
new_list.append(a * b)
</code></pre>
<p>这让我们非常清楚发生了什么,但是需要四行代码和对<code>new_list.append()</code>的重复调用,这有点低效。</p></li>
<li><p><strong>简洁</strong></p>
<pre><code>new_list = [a * b for a in list1 for b in list2]
</code></pre>
<p>这是非常紧凑的,但对于许多人来说,要记住多个<code>for</code><a href="https://docs.python.org/3/tutorial/datastructures.html#list-comprehensions" rel="nofollow noreferrer">list comprehensions</a>的嵌套是从左到右还是从右到左,需要一两分钟。</p></li>
<li><p><strong>懒惰</strong></p>
<pre><code>from itertools import product
new_list = [a * b for a, b in product(list1, list2)]
</code></pre>
<p>即使<code>list1</code>和<code>list2</code>是<a href="https://docs.python.org/3/glossary.html#term-generator" rel="nofollow noreferrer">generators</a>或其他一次性、延迟评估的iterables,例如</p>
<pre><code>>>> from itertools import count, islice
>>> list1 = islice(count(1), 3)
>>> list2 = islice(count(4), 3)
>>> [a * b for a, b in product(list1, list2)]
[4, 5, 6, 8, 10, 12, 12, 15, 18]
</code></pre>
<p>。。。前两种方法都不行。</p></li>
</ol>
<p>注意,在这些示例中,我使用了<code>new_list</code>而不是<code>NewList</code>,这是Python中命名变量的常规方法。你知道吗</p>