Pythonic love

justin walters walters.justin01 at gmail.com
Tue Mar 8 11:49:43 EST 2016


Correct me if I'm wrong, but don't python generators usually use the yield
statement so they can be used in list comprehensions?
On Mar 8, 2016 5:27 AM, "jmp" <jeanmichel at sequans.com> wrote:

> 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
>
>
>
>
> --
> https://mail.python.org/mailman/listinfo/python-list
>



More information about the Python-list mailing list