87 points · by jnoller · 15y ago · 12 comments
c.most_common()[:-n:-1] # n least common elements
For the love of ceiling_cat, how hard is it to implement a least_common method? reversed(c.most_common())
Although I agree that a least_common function would be more "symmetrical" (don't ask me why c has one and not both), you can create it yourself (and have it not only readable but efficient!) in one line of code.I don't know anything of the specifics of partial sorting but if the argument did what you suggest I'd guess the code would have a line like:
# Deal only with the first n items.
items = items[:n]
As it would make the code much simpler (quoting from The Zen Of Python, "special cases aren't special enough to break the rules"—we don't need a partial sort).[1] http://docs.python.org/library/collections.html#counter-obje...
def least_common(c, n=None):
key = operator.itemgetter(1)
if n is None:
return sorted(c.items(), key=key)
return heapq.nsmallest(n, c.items(), key=key)
It has the same efficiency as Counter.most_common(). c.most_common()[:-n-1:-1]
because the element at c.most_common()[-n]
is actually the n-1th most common element.Easy AI with Python: http://us.pycon.org/2009/conference/schedule/event/71/
Four powerful examples of composing Python tools: http://us.pycon.org/2010/conference/schedule/event/86/
Fun with Python's Newer Tools: http://blip.tv/file/4883247
http://docs.python.org/reference/lexical_analysis.html#strin...