Wednesday, October 12, 2011

Python list comprehension

I've written about Python list magic in the past and here's another tip:

Say you wanna create a list based on some other list, possibly filtering out certain entries and/or modifying the ones you choose to include.

Rather than this:

result = []
for item in mylist:
  if item > 5:
    result.append( '%05d'%item )

give this a go next time:

result = [ '%05d'%item for item in mylist if item>5 ]

Pretty neat, huh? Obviously this works on all valid sources of list data:

print 'Modules with \'site\' in the name:\n%s'%'\n'.join( \
      ['%s : %s'%(name,module) for name,module in \
        sys.modules.iteritems() if  'site' in name] )

Once we know this pattern it's fairly straightforward to create nested versions thereof, like this one straight out of a Maya script:

for attr in \
    [ '%s%s'%(attr,dim) for attr in ['t','r','s'] \ 
                         for dim in ['x','y','z'] ]:
  maya.cmds.connectAttr('%s.%s'%(sourceNode,attr), \
                        '%s.%s'%(targetNode,attr), f=True)

which combines two lists into one sequence of Maya attributes ['tx','ty','tz','rx','ry'... ] to connect between two nodes.

Expressive and neat, just the way I like it.

No comments:

Post a Comment