Re: Good Python style?



On May 31, 3:59 am, Andreas Beyer <m...@xxxxxxxxxx> wrote:
Hi,

I found the following quite cryptic code, which basically reads the
first column of some_file into a set.
In Python I am used to seeing much more verbose/explicit code. However,
the example below _may_ actually be faster than the usual "for line in ..."
Do you consider this code good Python style? Or would you recommend to
refrain from such complex single-line code??

Thanks!
Andreas

inp = resource(some_file)
# read first entries of all non-empty lines into a set
some_set = frozenset([line.split()[0] for line in \
filter(None, [ln.strip() for ln in inp])])

I think it would be more readable if you would take the filter out of
the list comprehension, and the list comprehension out of the set.

inp = resource(some_file)
stripped_lines = (ln.strip() for ln in inp)
splitted_lines = (line.split()[0] for line in stripped_lines if line)
some_set = frozenset(splitted_lines)

.



Relevant Pages

  • Re: Good Python style?
    ... I found the following quite cryptic code, ... first column of some_file into a set. ... In Python I am used to seeing much more verbose/explicit code. ... for line in inp ...
    (comp.lang.python)
  • Re: maximum value in a column of file
    ... bash, but i'm learning python), that the reason why i tried to use numpy. ... X.mean# mean of first column ... The scipy add-on contains a bunch of things for file i/o; ...
    (comp.lang.python)
  • Good Python style?
    ... I found the following quite cryptic code, ... first column of some_file into a set. ... In Python I am used to seeing much more verbose/explicit code. ... # read first entries of all non-empty lines into a set ...
    (comp.lang.python)
  • Re: Good Python style?
    ... I found the following quite cryptic code, ... first column of some_file into a set. ... In Python I am used to seeing much more verbose/explicit code. ... filter(None, # strip whitespace and filter out blank lines ...
    (comp.lang.python)
  • File Parsing Question
    ... for line in inp: ... I cannot push that operation here ... This works perfectly in Perl. ... Can I do the same in Python. ...
    (comp.lang.python)