擅长:python、mysql、java
<p>既然您使用的是<code>Counter</code>,请明智地使用它:</p>
<pre><code>import collections
def nth_most(str_in, n):
c = sorted(collections.Counter(w.lower() for w in str_in.split()).items(),key = lambda x:x[1])
return(list(c[-n])) # convert to list as it seems to be the expected output
print(nth_most("apple apple apple blue BlUe call",2))
</code></pre>
<p>建立词频字典,根据值(元组的第二个元素)对项目进行排序,并选择最后第n个元素。在</p>
<p>这将打印<code>['blue', 2]</code>。在</p>
<p>如果在第一位或第二位有两个频率相同的单词(并列)怎么办?这个解决方案行不通。相反,对出现的次数进行排序,提取第n个最常见的出现,然后再次运行counter dict来提取匹配项。在</p>
^{pr2}$
<p>这次打印:</p>
<pre><code>[['call', 2], ['blue', 2]]
</code></pre>