Please help for Python programming

bruno modulix onurb at xiludom.gro
Thu Mar 24 10:42:09 CET 2005


yy0127 at gmail.com wrote:
> I am sorry that i forgot to see the working example. Base on your
> example, i can show the value without missing but got the other
> problem. I would like to culmulate the value by users. 

This is (almost) exactly the same.

> I was rewrite
> your example but cannot not work.
> 
> ##
> import sys
> import pprint
> 
> try:
>     f = open('data.txt', 'r')
> except IOError, e:
>     print >> sys.stderr, "Cannot open file data.txt for reading : %s"
> %e
>     sys.exit(1)
> 
> users = {}
> cumdata2 = 0
> cumdata3 = 0
> for line in f:
> 
>     try:
>         user, data1, data2 = line.strip().split('\t')
>     except ValueError:
>         print >> sys.stderr, "wrong file format"
>         f.close()
>         sys.exit(1)
>     try:
>         users[user].append("%s : %s" % (data1, data2))
>         cumdata2 = int(data2) + cumdata2

Q1 : What do you think this will do ?

>     except KeyError:
>         users[user] = ["%s : %s" % (data1, data2)]
>         cumdata3 = int(data2) + cumdata3

Q2 : What do you think this will do ?

> f.close()
> print "collected data:"
> pprint.pprint(users)
> print cumdata2
> print cumdata3
> ##
> 
> The above example can run but the total num are wrong. 

First, please post your test data set, the expected result and the 
actual result. Saying 'the total num is wrong' doesn't give a clue.

> Would you mind
> to figure out where is my problem?

I may be wrong (pun intended), but I think you don't really understand 
what this code is doing, specially this part :

try:
   users[user].append(something)
except KeyError:
   users[user] = [something]

In fact I think your problem is that you still have not read the fine 
manual, specially the part about dicts.

Read the manual, understand the above snippet - which is a pretty common 
idiom in Python -, try to answer Q1 and Q2, and you should be able to 
work it out by yourself.

-- 
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for 
p in 'onurb at xiludom.gro'.split('@')])"



More information about the Python-list mailing list