[Tutor] Simple counter to determine frequencies of words in adocument

Alan Gauld alan.gauld at btinternet.com
Sun Nov 21 19:19:25 CET 2010


"Josep M. Fontana" <josep.m.fontana at gmail.com> wrote

> : return sorted(
> : word_table.items(), key=lambda item: item[1], reverse=True
> : )

> By the way, I know what a lambda function is and I read about the 
> key
> parameter in sorted() but I don't understand very well what
> "key=lambda item: item[1]" does.
...
> ....What I don't understand is the syntax of "item : item[1]".

OK,
So you know that a lambda is an anonymous function and

g = lambda x: f(x)

can be rewritten as:

def g(x):
    return f(x)

So in your case you could have done:

def getSecond(item):
     return item[1]

return sorted( word_table.items(), key=getSecond, reverse=True)

So reverse engineering that we get

lambda item: item[1]

item is the parameter of the anonymous function.
and item[1] is the return value. (The colon separates parameter
from return value)

> > Once you gain familiarity with the lists and dicts, you can try 
> > out
> > collections, as suggested by Peter Otten.
>
> The problem is that I'm using version 2.6.1. I have a Mac and I am
> using a package called NLTK to process natural language.

Thats no problem. 2.6 is a recent version of Puython, I see
no reason to change Python version for now. You can run other
python versions on the Mac alongside your default install but
for now you have no good reason to do so. Keep life simple :-)

HTH,

-- 
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/




More information about the Tutor mailing list