help with simple script and strings
Kyle VanderBeek
kylev at kylev.com
Sat Apr 12 20:47:25 UTC 2008
On Sat, Apr 12, 2008 at 01:35:33PM -0700, John Poelstra wrote:
> directories = ['20080412', '20080324', 'blahblah', 'latest-dir',
> 'rawhide-20080410', 'rawhide-20080411', 'rawhide-20080412' , '20080401']
>
> print 'directories == %s' % directories
>
> for directory in directories:
> print 'processing directory %s ' % directory
> if not directory.startswith('200'):
> directories.remove(directory)
> print 'removed == %s' % directory
>
> print 'directories == %s' % directories
Modifying the contents of a list that you're iterating over with a
generator will give you strange results. Basically, you're causing the
generator to lose its place. If you put the result in a new list (say,
directories_new), this won't happen.
Granted, I'd probably do it this way, just going once over the list with
a list iteration:
>>> [d for d in directories if d.startswith('200')]
['20080412', '20080324', '20080401']
Since it builds a new list, you can even assign it back to the
directories variable:
>>> directories = [d for d in directories if d.startswith('200')]
>>> directories
['20080412', '20080324', '20080401']
I'm not a huge fan of list comprehensions due to the somewhat baroque
syntax, but this seems like a perfect single-pass O(n) application of
the construct that is still easy to read.
--
kylev at kylev.com
Some people have a way with words, while others... erm... thingy.
More information about the Fedora-python-devel-list
mailing list