[Tutor] Need help with dict.calculation

Eve Kotyk e.kotyk@shaw.ca
Fri, 25 Jan 2002 00:22:01 +0000


Sean 'Shaleh' Perry wrote:

Thanks I'll store this in my Python file for further reference.  I can't
say I totally understand it but will continue to think about it.
 
> I have been writing a program at work which reads a log and keeps a running
> count of machine reboots per machine.  A nifty way to handle the increment is
> the get() method of dictionaries.
> 
> dict[key] = dict.get(key, 0) + 1
> 
> OK, so this doesn't help directly, but I thought I would share.  Onto the real
> help.
> 
> Another useful python function is 'reduce'.  reduce takes a list and runs a
> function on each item in the list plus a running variable.
> 
> from above I have:
> 
> import operator
> count = reduce(operator.add, dict.values())
> print "Total reboot count for all machines was " + count
> 
> What reduce does is more clear if I show you what operator.add looks like:
> 
> def add(x, y):
>     return x + y
> 
> so what the reduce function does internally is basically:
> 
> value = 0
> for item in list:
>     value = function(value, item)
> return value
> 
> Hope this gives you some glimpses of python's abilities.

-- 

ekotyk

http://members.shaw.ca/e.kotyk/virtualstudio.htm