确定您在 python 的循环中正在进行哪个迭代 [英] Identify which iteration you are on in a loop in python

查看:25
本文介绍了确定您在 python 的循环中正在进行哪个迭代的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

基本上,我希望能够知道我何时在循环迭代中的第 N 个项目上.有什么想法吗?

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: # <-- this line is psuedo code
        print "last item :", x
    else:
        print x

推荐答案

使用 枚举:

#!/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

这篇关于确定您在 python 的循环中正在进行哪个迭代的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆