Re: Is there a better/simpler way to filter blank lines?



On Nov 4, 3:30 pm, tmallen <thomasmal...@xxxxxxxxx> wrote:
On Nov 4, 4:30 pm, bearophileH...@xxxxxxxxx wrote:

tmallen:

I'm parsing some text files, and I want to strip blank lines in the
process. Is there a simpler way to do this than what I have here?
lines = filter(lambda line: len(line.strip()) > 0, lines)

xlines = (line for line in open(filename) if line.strip())

Bye,
bearophile

I must be missing something:

xlines = (line for line in open("new.data") if line.strip())
xlines

<generator object at 0x6b648>>>> xlines.sort()

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'generator' object has no attribute 'sort'

What do you think?

Thomas

Using the surrounding parentheses creates a generator object, whereas
using square brackets would create a list. So, if you want to run list
operations on the resulting object, you'll want to use the list
comprehension instead.

i.e.

list_o_lines = [line for line in open(filename) if line.strip()]

Downside is the increased memory usage and processing time as you dump
the entire file into memory, whereas if you plan to do a "for line in
xlines:" operation, it would be faster to use the generator.
.



Relevant Pages

  • Re: Is there a better/simpler way to filter blank lines?
    ... I must be missing something: ... A generator is a ... sequence, ... for line in xlines: ...
    (comp.lang.python)
  • Re: Is there a better/simpler way to filter blank lines?
    ... Using the surrounding parentheses creates a generator object, ... Downside is the increased memory usage and processing time as you dump ... xlines:" operation, it would be faster to use the generator. ...
    (comp.lang.python)
  • Re: Populating a dictionary, fast
    ... code, while correct in intent, does look a bit fishy (missing those ... By "missing those square brackets", what would be a list comprehension ... Enter 'python "generator expression"' into your favourite search ...
    (comp.lang.python)
  • Re: define "generator" (glossary bug?)
    ... >>> and has used instead the definition for 'generator function', ... >>> which term is missing from the glossary. ... America's vaunted "free press" notwithstanding, ... -- Jim Thornton ...
    (comp.lang.python)
  • About 1.8.7 Array#map! without a block
    ... with e.next to change the value, say, multiplying by 2 as on the first ... case and have a array on the end? ... - Why I get a Generator on "a" elements when I just call e.next? ... cause it's what I'm missing to use with next, ...
    (comp.lang.ruby)