for loop question
Tim Chase
python.list at tim.thechases.com
Wed Oct 10 16:45:47 EDT 2007
Paul Hankin wrote:
> On Oct 10, 9:12 pm, Tim Chase <python.l... at tim.thechases.com> wrote:
>> >>> pairs = (test[i:i+2] for i in xrange(len(test)-1))
>> >>> for a,b in pairs:
>> ... print a,b
>
> for a, b in zip(test, test[1:]):
> print a, b
Very nice!
I second this solution as better than my original. The only
"improvement" (in quotes, because it might be more work/opacity
than the problem merits) might be to use izip/islice from
itertools to do the evaluation lazily if "test" gets large:
from itertools import izip, islice
for a,b in izip(test, islice(test, 1, None)):
print a,b
[side note/question]
What's with islice having the first optional paramenter expand as
the stop/third argument by default:
islice(test, 1) -> stop at 1
islice(test, 1, 2) -> start at 1, stop at 2
islice (in python2.4) doesn't even take kword params, so you
can't force it like
islice(test, start=1)
but instead must specify a stop parameter, even if it's None:
islice(test, 1, None)
Seems bogus, IMHO.
-tkc
More information about the Python-list
mailing list