how to get the next obj in this place
this is my python code :
a=['aaa','bbb','oooo'开发者_Go百科,'qqqq','gggg']
for i in a:
print i #how to get the next obj in this place .
i want to get next code when i get the i
element ,
thanks
You could use the zip
function to get both the current and next item in the list in the for
loop. So the for
loop is iterating through the list and the list offset by 1 at the same time:
for this,after in zip(a,a[1:]):
print this,after
However, zip
stops at the end of the shortest list so you won't get to process the last element of your list. If this is a problem use izip_longest
from itertools
.
import itertools
for this,after in itertools.izip_longest(a,a[1:]):
print this,after
In this case after
will be None
for the last item in the list.
izip_longest
was introduced in Python 2.6 so if you're running an earlier version you could achieve the same effect by hand by appending None
on to the end of the shorter list:
for this,after in zip(a,a[1:] + [None]):
print this,after
You can use {% for x, y in somelist %}
in a Django template but you would need do the zip
in your model and store that in a variable passed to the template.
It's easier just to enumerate the list for this:
a=['aaa','bbb','oooo','qqqq','gggg']
for idx, item in enumerate(a):
print item
if idx < len(a)-1:
print a[idx+1]
(edit: fixed for IndexError
)
>>> def twobytwo(it, last_single=False):
... guard = object()
... oe = guard
... for e in it:
... if oe != guard:
... yield oe, e
... oe = e
... if oe != guard and last_single:
... yield oe, None
...
>>> for a, b in twobytwo(['aaa','bbb','oooo','qqqq','gggg']):
... print a, b
...
aaa bbb
bbb oooo
oooo qqqq
qqqq gggg
>>> for a, b in twobytwo(['aaa','bbb','oooo','qqqq','gggg'], last_single=True):
... print a, b
...
aaa bbb
bbb oooo
oooo qqqq
qqqq gggg
gggg None
>>>
精彩评论