[Tutor] for loop issue
Rich Lovely
roadierich at googlemail.com
Sat Oct 10 19:07:15 CEST 2009
2009/10/9 Oxymoron <moron.oxy at gmail.com>:
> On Fri, Oct 9, 2009 at 11:02 PM, Kent Johnson <kent37 at tds.net> wrote:
>> On Fri, Oct 9, 2009 at 3:54 AM, Stefan Lesicnik <stefan at lsd.co.za> wrote:
>>
>> You can easily keep track of the previous item by assigning it to a
>> variable. For example this shows just the increasing elements of a
>> sequence:
>>
>> In [22]: items = [0, 1, 3, 2, 8, 5, 9 ]
>>
>> In [23]: last = None
>>
>> In [24]: for item in items:
>> ....: if last is None or item > last:
>> ....: print item
>> ....: last = item
>
> Darn... this is what happens when you're stuck on one solution
> (referring to my index-only ways in the last post) - you miss other
> obvious ways, duh * 10. Apologies for the unnecessarily complicated
> exposition on iterables above. :-(
>
>
>
> --
> There is more to life than increasing its speed.
> -- Mahatma Gandhi
> _______________________________________________
> Tutor maillist - Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
Another way, if you just want to track two consecutive items (which
probably won't help in this case, but is useful to know), is to zip
together two iters over the list, one omitting the first item, the
other omitting the last:
>>> lst = range(5)
>>> for v1, v2 in zip(lst[:-1], lst[1:]):
... print v1, v2
...
0 1
1 2
2 3
3 4
4 5
If you're concerned about memory usage (zip generates an intermediate
list, twice the size of the original), you can use itertools.izip,
which is the same except it doen't generate the list: it's xrange to
zip's range.
Also, rather than mucking around with xrange() and len(), I'd always
recommend using enumerate:
e.g. Your example of
for i in xrange(0, len(x)-1):
print x[i], x[i+1]
becomes
for i, v in enumerate(x[:-1]): #omitting last value in list to avoid IndexError
print v, x[i+1]
I've got to say that of the two, I prefer the zip method: it looks
cleaner, at least to my eyes.
--
Rich "Roadie Rich" Lovely
There are 10 types of people in the world: those who know binary,
those who do not, and those who are off by one.
More information about the Tutor
mailing list