Identify which iteration you are on in a loop in python

匿名 (未验证) 提交于 2019-12-03 01:27:01

问题:

Basically I would like to be able to tell when I'm on the Nth item in a loop iteration. Any thoughts?

d = {1:2, 3:4, 5:6, 7:8, 9:0}  for x in d:     if last item: # 

回答1:

Use enumerate:

#!/usr/bin/env python  d = {1:2, 3:4, 5:6, 7:8, 9:0}  # If you want an ordered dictionary (and have python 2.7/3.2),  # uncomment the next lines:  # from collections import OrderedDict # d = OrderedDict(sorted(d.items(), key=lambda t: t[0]))  last = len(d) - 1  for i, x in enumerate(d):     if i == last:         print i, x, 'last'     else:         print i, x  # Output: # 0 1 # 1 3 # 2 9 # 3 5 # 4 7 last 


回答2:

How about using enumerate?

>>> d = {1:2, 3:4, 5:6, 7:8, 9:0} >>> for i, v in enumerate(d): ...     print i, v              # i is the index ...  0 1 1 3 2 9 3 5 4 7 


回答3:

for x in d.keys()[:-1]:     print x if d: print "last item:", d.keys()[-1] 


回答4:

d = {1:2, 3:4, 5:6, 7:8, 9:0}  for i,x in enumerate(d):     print "last item :"+repr(x) if i+1==len(d) else x 

But the last item of an unordered dictionary doesn't mean anything



回答5:

list = [1,2,3]  last = list[-1]  for i in list:     if i == last:         print("Last:")     print i 

Output:

1 2 Last: 3 


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!