<p>您可以使用<a href="https://docs.python.org/3/library/itertools.html#itertools.groupby" rel="nofollow noreferrer">^{<cd1>}</a>创建一个<code>dict</code>,其中key是食品过期日期,value是它在列表中出现的次数</p>
<pre><code>>>> from itertools import groupby
>>> fridge = [Food("beer",4), Food("steak",1), Food("hamburger",1), Food("donut",3),]
>>> d = dict((k,len(list(v))) for k,v in groupby(sorted(l,key=lambda x: x.expiration), key=lambda x: x.expiration))
</code></pre>
<p>这里我们指定<code>groupby</code>来对列表中具有相同<code>expiration</code>的所有元素进行分组(<strong>注意<code>groupby</code>中的<code>key</code>参数)。groupby操作的输出大致相当于<code>(k,[v])</code>,其中<code>k</code>是组键,<code>[v]</code>是属于该特定组的值列表。你知道吗</p>
<p>这将产生如下输出:</p>
<pre><code>>>> d
>>> {1: 2, 3: 1, 4: 1}
</code></pre>
<p>在这一点上,我们有<code>expiration</code>和特定过期发生在一个列表中的次数,这个列表存储在dict<code>d</code>中。你知道吗</p>
<p>接下来,我们需要创建一个列表,以便如果dict<code>d</code>中存在一个元素,则输出它,否则输出<code>0</code>。我们需要在dict<code>d</code>键中从0迭代到max number。为此,我们可以:</p>
<pre><code>>>> [0 if not d.get(x) else d.get(x) for x in range(0, max(d.keys())+1)]
</code></pre>
<p>这将产生所需的输出</p>
<pre><code>>>> [0,2,0,1,1]
</code></pre>