Python: a use for nested list comprehensions
I wanted to turn a list like ['*.zip', '*.pyc', '*.log'] into ['--exclude', '*.zip', '--exclude', '*.pyc', '--exclude', '*.log'].
A simple list comprehension doesn’t work as desired:
In [1]: excludes = ['*.zip', '*.pyc', '*.log']
In [2]: [('--exclude', e) for e in excludes]
Out[2]: [('--exclude', '*.zip'), ('--exclude', '*.pyc'), ('--exclude', '*.log')]
The trick is to use a nested comprehension:
In [5]: [arg for pattern in excludes
for arg in ['--exclude', pattern]]
Out[5]: ['--exclude', '*.zip', '--exclude', '*.pyc', '--exclude', '*.log']
blog comments powered by Disqus