[Tutor] pruning and ordering a list of lists

Kent Johnson kent37 at tds.net
Sat Mar 24 04:13:58 CET 2007


William O'Higgins Witteman wrote:
> Thank you.  I found a similar solution myself while waiting.  I was
> stuck with thinking about the output being a list of lists, but once I
> thought of it as a dictionary the solution came much more easily.
> Here's the code, including timestamp conversions:
> 
> #!/usr/bin/python
> 
> import time
> 
> def userlists(usertimepairs):
>   
>   userandtoptimes = {}
>   for line in usertimepairs:

You can say
   for user, timestamp in usertimepairs:
and then refer to user and timestamp instead of line[0] and line[1]; it 
makes the code much more readable.

>     line[0] = line[0].lower()
>     if userandtoptimes.has_key(line[0]):
>       a = time.strptime(userandtoptimes[line[0]],"%d/%b/%Y:%H:%M:%S")
>       prevtime = time.mktime(a)

You might consider keeping prevtime in the dictionary instead of 
converting to and from strings all the time. You can convert them back 
to strings when you write them out. Then the above two lines would just be
   prevtime = userndtoptimes[user]

>       b = time.strptime(line[1],"%d/%b/%Y:%H:%M:%S -0400")
>       thistime = time.mktime(b)
>       if thistime > prevtime:
>         c = time.gmtime(thistime)
>         d = time.strftime("%d/%b/%Y:%H:%M:%S",c)
>         userandtoptimes[line[0]] = d

This could just be
   userandtoptimes[user] = thistime

>       else:
>         pass
>     else:
>       e = time.strptime(line[1],"%d/%b/%Y:%H:%M:%S -0400")
>       f = time.strftime("%d/%b/%Y:%H:%M:%S",e)
>       userandtoptimes[line[0]] = f
> 
>   #debug print(userandtoptimes)
> 
>   # Output to CSV file
>   for user, timestamp in userandtoptimes.iteritems():
>     op.write(user + "," + timestamp + "\n")

Here you would have to convert to a string.

Kent


More information about the Tutor mailing list