[Tutor] how to extract data only after a certain condition is met
Peter Otten
__peter__ at web.de
Wed Oct 6 19:12:52 CEST 2010
Eduardo Vieira wrote:
> The other day I was writing a script to extract data from a file from
> the line where a text is found to the end of the file. The same
> functionality is this sed script:
> '1,/regexp/'d
> I couldn't put my head to work around this and came up with a solution
> using list slicing. But how can I do that? I was experimenting with a
> simple list and I came up with this. I wonder if I shouldn't you a
> "while" statement, but how?
>
> a = ['m', 'a', 'r', 'i', 'g', 'o', 'l', 'd']
> b = True
>
> for letter in a:
> if letter != 'i' and b:
> continue
> elif letter == 'i':
> b = False
> else:
> print letter
>
> Ok. This works, but I wonder if I shouldn't you a "while" statement, but
> how?
I would use two for loops:
>>> a = ['m', 'a', 'r', 'i', 'g', 'o', 'l', 'd']
>>> ai = iter(a) # make a list iterator
>>> for letter in ai:
... if letter == "i": break
...
>>> for letter in ai:
... print letter
...
g
o
l
d
Normally a list iterator is created implicitly by writing
for item in some_list:
...
but here you have to make one explicitly because you want to reuse it in the
second loop.
Alternatively, the itertools module has the building blocks for this and
similar problems:
>>> from itertools import dropwhile, islice
>>> def not_an_i(letter):
... return letter != "i"
...
>>> for letter in dropwhile(not_an_i, a):
... print letter
...
i
g
o
l
d
OK, let's shave off the first item in the dropwhile(...) sequence:
>>> for letter in islice(dropwhile(not_an_i, a), 1, None):
... print letter
...
g
o
l
d
Peter
More information about the Tutor
mailing list