[OFF] sed equivalent of something easy in python

Arnaud Delobelle arnodel at gmail.com
Wed Oct 27 14:50:59 EDT 2010


Tim Chase <python.list at tim.thechases.com> writes:

> On 10/27/10 09:39, Jussi Piitulainen wrote:
>>> So, is there some simple expression in Python for this? Just asking
>>> out of curiosity when nothing comes to mind, not implying that there
>>> should be or that Python should be changed in any way.
>>
>> To expand, below is the best I can think of in Python 3 and I'm
>> curious if there is something much more concise built in that I am
>> missing.
>>
>> def sed(source, skip, keep, drop):
>>
>>      '''First skip some elements from source,
>>      then keep yielding some and dropping
>>      some: sed(source, 1, 2, 3) to skip 1,
>>      yield 2, drop 3, yield 2, drop 3, ...'''
>>
>>      for _ in range(0, skip):
>>          next(source)
>>      while True:
>>          for _ in range(0, keep):
>>              yield next(source)
>>          for _ in range(0, drop):
>>              next(source)
>
> Could be done as:  (py2.x in this case, adjust accordingly for 3.x)
>
>   def sed(source, skip, keep, drop):
>     for _ in range(skip): source.next()
>     tot = keep + drop
>     for i, item in enumerate(source):
>       if i % tot < keep:
>         yield item
>
> -tkc

With Python 2.7+ you can use itertools.compress:

>>> from itertools import *
>>> def sed(source, skip, keep, drop):
...  return compress(source, chain([0]*skip, cycle([1]*keep + [0]*drop)))
... 
>>> list(sed(range(20), 1, 2, 3))
[1, 2, 6, 7, 11, 12, 16, 17]

-- 
Arnaud



More information about the Python-list mailing list