TE
科技回声
首页24小时热榜最新最佳问答展示工作
GitHubTwitter
首页

科技回声

基于 Next.js 构建的科技新闻平台,提供全球科技新闻和讨论内容。

GitHubTwitter

首页

首页最新最佳问答展示工作

资源链接

HackerNews API原版 HackerNewsNext.js

© 2025 科技回声. 版权所有。

Counting elements with dictionary

2 点作者 kracekumar大约 11 年前

1 comment

dalke大约 11 年前
That was the Pythonic approach until 2006. With Python 2.5 the Pythonic solution was often to use defaultdict:<p><pre><code> &gt;&gt;&gt; from collections import defaultdict &gt;&gt;&gt; words = [&#x27;a&#x27;, &#x27;the&#x27;, &#x27;an&#x27;, &#x27;a&#x27;, &#x27;an&#x27;, &#x27;the&#x27;] &gt;&gt;&gt; d = defaultdict(int) &gt;&gt;&gt; for word in words: ... d[word] += 1 ... &gt;&gt;&gt; d defaultdict(&lt;type &#x27;int&#x27;&gt;, {&#x27;a&#x27;: 2, &#x27;the&#x27;: 2, &#x27;an&#x27;: 2}) </code></pre> It&#x27;s a bit more cumbersome, but the performance is better, and defaultdict(list)[key].append() is much better than setdefault(key, []).append(value).<p>In modern Python (starting with Python 2.7, released in 2010), the Pythonic solution is collections.Counter:<p><pre><code> &gt;&gt;&gt; from collections import Counter &gt;&gt;&gt; words = [&#x27;a&#x27;, &#x27;the&#x27;, &#x27;an&#x27;, &#x27;a&#x27;, &#x27;an&#x27;, &#x27;the&#x27;] &gt;&gt;&gt; Counter(words) Counter({&#x27;a&#x27;: 2, &#x27;the&#x27;: 2, &#x27;an&#x27;: 2}) </code></pre> or dict(Counter(words)) if you want the result to return an actual dict instead of a Counter instance.