How do I speedup this loop?
gry at ll.mit.edu
Thu Jul 15 03:10:20 CEST 2004
On Wed, 14 Jul 2004 15:40:15 -0400
Bart Nessux <bart_nessux at hotmail.com> threw this fish to the penguins:
> george young wrote:
> > How about:
> > lines = 
> > out = os.popen('some command')
> > for l in out:
> > lines.append(l.strip())
> > script = ''.join(lines)
> > out.close()
> > The "strip" actually removes white space from front and back of the string;
> > you could say l.strip('\n') if you only want the newlines removed (or '\r'
> > if they're really carriage return characters.)
> The above is a great solution... should make for a good speed up. It's
> how I might pproach it.
> > Or if you want a clever (and most CPU efficient!) one-liner:
> > script = ''.join([l.strip() for l in os.popen('some command')])
[fixed up a bit...I forgot about the join]
> Clever progammers should be shot! I've had to work behind them... they
> are too smart for their own good. They think everyone else in the world
> is as clever as they are... this is where they are wrong ;)
Oh, all right. How about:
out = os.popen('some command')
temp_script = [l.strip() for l in out]
script = ''.join(temp_script)
That's clear enough, and still takes advantage of the efficiency of
the list comprehension! (I admit, that for reading the whole file,
the other postings of regexp substitution on the total string are
certainly faster, given enough RAM, but still not as clear and concise
and elegant ... blah blah blah as mine...
-- George Young
"Are the gods not just?" "Oh no, child.
What would become of us if they were?" (CSL)
More information about the Python-list