I use Python list and dict comprehension heavily these days. To ask me to stop using them would be like asking Angus Young to stand up while he plays guitar.
Instead of doing this…
1 2 3 4 5 6 |
# The long and slow way lod0Meshes = [] for groupMesh in group.getChildren(): # Append any meshes with lod0 if re.search('_lod0', groupMesh.name()): lod0Meshes.append(groupMesh) |
…you can do this:
1 2 |
# List comprehension (Python sugar) lod0Meshes = [ groupMesh for groupMesh in group.getChildren() if re.search('_lod0', groupMesh.name()) ] |
List comprehension allows you to build a list in a single line and include conditional statements as part of it.
Instead of just storing the list in a variable, you could act on it right away:
1 2 3 |
# List comprehension (Python sugar) for lod0Mesh in [ groupMesh for groupMesh in group.getChildren() if re.search('_lod0', groupMesh.name()) ]: doSomething |
I love to be able to remove potential duplicate list entries from the built list before I act on it.
1 2 3 |
# Removing duplicates in list comprehension for itemId in list(set([ item.id for item in items if item.type == 'groovy'])): doSomething |
Another handy use is to filter file extensions when using os.walk:
1 2 3 4 5 6 7 8 |
#Extension type list comprehension import os import fnmatch for path, dirs, files in os.walk(os.path.abspath(startPath)): for xml in [filename for filename in files if fnmatch.fnmatch(filename, '*.xml')]: doSomething |
In the example below, we go through attributes and only act on the attributes that are not part of an exclude list of attributes that we have.
1 2 3 4 5 |
#PyMel list comprehension for hlslShader in hlslShaders: for shaderAttr in [shaderAttr for shaderAttr in hlslShader.listAttr() if not shaderAttr.name(includeNode=False) in excluded]: doSomething |
Finally, here is how to use the same awesome sauce with dictionaries.
1 2 3 |
#Dictionary comprehension newDictionary = {key:value for key, value in iterable} |
Do you guys have more goodness to share as it relates to list comprehension?
Will this change your lives forever?
Feel free to comment below.
Spread the knowledge