In django templates I accomplish this with {% if forloop.first %}
but im not sure how to do t开发者_开发知识库his in regular 'ole python without writing a clunky counter to count up as my conditional iterates. Is their an easy way out?
Take a look at enumerate
.
Return an enumerate object. sequence must be a sequence, an iterator, or some other object which supports iteration. The next() method of the iterator returned by enumerate() returns a tuple containing a count (from start which defaults to 0) and the corresponding value obtained from iterating over iterable. enumerate() is useful for obtaining an indexed series ...
>>> for i, season in enumerate(['Spring', 'Summer', 'Fall', 'Winter']):
... print i, season
0 Spring
1 Summer
2 Fall
3 Winter
精彩评论