pattern matching with multiple lists

MRAB python at mrabarnett.plus.com
Fri Jul 16 16:29:16 EDT 2010


Chad Kellerman wrote:
> Greetings,
>      I have some code that I wrote and know there is a better way to
> write it.  I  wonder if anyone could point me in the right direction
> on making this 'cleaner'.
> 
>      I have two lists:   liveHostList = [ app11, app12, web11, web12, host11 ]
>                                     stageHostList      = [  web21,
> web22, host21, app21, app22 ]
> 
>      I need to pair the elements in the list such that:
>     app11  pairs with app21
>     app12 pairs with app22
>     web11 pairs with web21
>     web12 pairs with web22
>     host11pairs with host21
> 
>     each time I get the list I don't know the order, and the lists
> will grow over time.  (hosts will be added in pairs.  app13 to
> liveHostList and app23 to stageHostList, etc)
> 
> 
> Anyways this is what I have.  I think it can be written better with
> map, but not sure.  Any help would be appreciated.
> 
> import re
> for liveHost in liveHostlist:
> 
>     nameList = list(liveHost)
>     clone    = nameList[-1]
>     di       = nameList[-2]
>     generic  = liveHost[:-2]
> 
>     for stageHost in stageHostList:
>         if re.match( generic + '.' + clone, stageHost ):
>             print "Got a pair: " + stageHost + liveHost
> 
> Thanks again for any suggestions,
> Chad
> 
So you recognise a pair by them having the same 'key', which is:

     name[ : -2] + name[-1 : ]


Therefore you can put one of the lists into a dict and look up the name
by its key:

     liveHostDict = dict((liveHost[ : -2] + liveHost[-1 : ], liveHost) 
for liveHost in liveHostList)

     for stageHost in stageHostList:
         key = stageHost[ : -2] + stageHost[-1 : ]
         liveHost = liveHostDict[key]
         print "Got a pair: %s %s" % (stageHost, liveHost)




More information about the Python-list mailing list