如何解决确定您在python循环中正在进行的迭代
用途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
解决方法
基本上,我希望能够在循环迭代中确定何时进入第N个项目。有什么想法吗?
d = {1:2,3:4,5:6,7:8,9:0}
for x in d:
if last item: # <-- this line is psuedo code
print "last item :",x
else:
print x
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。