Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #104334

Re: Pythonic love

From jmp <jeanmichel@sequans.com>
Newsgroups comp.lang.python
Subject Re: Pythonic love
Date 2016-03-08 14:25 +0100
Message-ID <mailman.42.1457443519.15725.python-list@python.org> (permalink)
References <nbl0lo$5o5$1@gioia.aioe.org>

Show all headers | View raw


On 03/07/2016 11:51 PM, Fillmore wrote:
>
> learning Python from Perl here. Want to do things as Pythonicly as
> possible.
>
> I am reading a TSV, but need to skip the first 5 lines. The following
> works, but wonder if there's a more pythonc way to do things. Thanks
>
> ctr = 0
> with open(prfile,mode="rt",encoding='utf-8') as pfile:
>      for line in pfile:
>          ctr += 1
>
>          if ctr < 5:
>              continue
>
>          allVals = line.strip().split("\t")
>          print(allVals)

what about a generator expression ? The (not so)new hype:

with open(prfile,mode="rt",encoding='utf-8') as pfile:
   for values in (l.strip().split("\t") for (i, l) in enumerate(pfile) 
if i >=5):
     print values

slightly dense, could be better with a lambda function

tovalues = lambda l: l.strip().split("\t")
with open(prfile,mode="rt",encoding='utf-8') as pfile:
   for values in (tovalues(l) for (i, l) in enumerate(pfile) if i >=5):
     print values


This should even work quite efficiently on big files, because I don't 
thing no more than one line is in memory at a given time.

jm



Back to comp.lang.python | Previous | NextPrevious in thread | Next in thread | Find similar | Unroll thread


Thread

Pythonic love Fillmore <fillmore_remove@hotmail.com> - 2016-03-07 17:51 -0500
  Re: Pythonic love Rob Gaddi <rgaddi@highlandtechnology.invalid> - 2016-03-07 22:52 +0000
  Re: Pythonic love sohcahtoa82@gmail.com - 2016-03-07 15:03 -0800
    Re: Pythonic love Fillmore <fillmore_remove@hotmail.com> - 2016-03-07 18:12 -0500
  Re: Pythonic love Ian Kelly <ian.g.kelly@gmail.com> - 2016-03-07 16:13 -0700
  Re: Pythonic love Mark Lawrence <breamoreboy@yahoo.co.uk> - 2016-03-07 23:19 +0000
  Re: Pythonic love jmp <jeanmichel@sequans.com> - 2016-03-08 14:25 +0100
  Re: Pythonic love justin walters <walters.justin01@gmail.com> - 2016-03-08 08:49 -0800
  Re: Pythonic love Mark Lawrence <breamoreboy@yahoo.co.uk> - 2016-03-08 16:55 +0000
  Re: Pythonic love jmp <jeanmichel@sequans.com> - 2016-03-08 18:00 +0100
  Re: Pythonic love justin walters <walters.justin01@gmail.com> - 2016-03-08 09:17 -0800
    Re: Pythonic love jstitch@invernalia.homelinux.net (Javier Novoa C.) - 2016-03-08 11:27 -0600
      Re: Pythonic love Dennis Lee Bieber <wlfraed@ix.netcom.com> - 2016-03-08 21:10 -0500

csiph-web