python - 确定您在 python 循环中进行的迭代

标签 python loops dictionary iterator

基本上,我希望能够知道我何时在循环迭代中的第 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

最佳答案

使用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

关于python - 确定您在 python 循环中进行的迭代,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4751092/

相关文章:

python - Django:为什么 'Class' 对象不可迭代

ios - 循环字典数组中的元素

javascript - async.each 有问题,回调在完成任务之前被调用

javascript - 循环遍历对象并显示输入字段

python - 字典组合 - 不等数量的键和值

dictionary - 如何在 Julia 中使用带有复杂字典键的 husky() 和 in() 函数?

python - 确定 Perl 模块中的相对路径

python - 将 time.time() 秒转换为当前时间,格式为 hh :mm:ss in python

python - 在 numpy 复合数据集中填充值很慢;为什么?

python - 在python中返回wavfile.read的类型