开发者

conditional iterators in Python: How can I pick out a particular iteration?

开发者 https://www.devze.com 2023-02-04 18:34 出处:网络
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

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
0

精彩评论

暂无评论...
验证码 换一张
取 消