擅长:python、mysql、java
<pre><code>weights = [('apple', 5), ('banana', 9), ('coconut', 14)]
prices = [('apple', 0.99), ('banana', 1.24), ('coconut', 3.20)]
</code></pre>
<p>您可以使用字典理解将这两个列表转换为字典,以水果作为键</p>
<pre><code>weights = {fruit:weight for fruit, weight in weights}
prices = {fruit:price for fruit, price in prices}
</code></pre>
<p>这个步骤可以简单地用<code>dict</code>函数编写,如下所示</p>
<pre><code>weights, prices = dict(weights), dict(prices)
</code></pre>
<p>然后列表的构造是琐碎的,需要列表理解</p>
<pre><code>print [(fruit, weights[fruit], prices[fruit]) for fruit in weights]
# [('coconut', 14, 3.2), ('apple', 5, 0.99), ('banana', 9, 1.24)]
</code></pre>