Having fun with python

Duncan Booth duncan.booth at invalid.invalid
Wed Oct 3 04:48:32 EDT 2007


Tzury <Afro.Systems at gmail.com> wrote:

>     def loadResMap(self):
>         self.resMap = []
>         [[self.resMap.append(str('A2' + sim[0] + '/r' + str(x)))
>             for x in range(1, eval(sim[1])+1)]
>                 for sim in [x.split(':')
>                     for x in quickViews.smsResList.v.split(",")]]
>         '''
>         # Confused? Have this one:
> 
>         data = quickViews.smsResList.v
>         sims, slots = [], data.split(",")
>         for slot in slots:
>             sims.append(slot.split(':'))
>         for sim in sims:
>             for x in range(1, eval(sim[1])+1):
>                 self.resMap.append(str('A2' + sim[0] + '/r' +
> str(x)))
> 
>         # same functionality different approaches
>         # forloops vs. list comprehension
>         # redability vs. smartassicity
>         # AKA: You have read too many Lisp books
>         '''
> 
The first one is stupid because it build a list of None objects and then 
throws it away.

The second one goes too far avoiding all list comprehensions:

   sims = [ slot.split(':')
     for slot in quickViews.smsResList.v.split(',') ]

is perfectly manageable, although it looks like there should be a method 
'getSims' on quickviews or smsResList or something that returns the data 
in the correct (already split) format.

The 'eval' is almost certainly a mistake in both variants. Probably you 
just meant to call 'int'. Also a format string would be clearer:

   for a, b in sims:
      self.resMap.extend("A2%s/r%d" % (a, x+1)) for x in range(int(b)))

However, one point you have shown very clearly: the second one is much 
easier to tear apart and reassemble.



More information about the Python-list mailing list