且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

确定你在python循环中的迭代

更新时间:2022-12-30 13:23:54

a href =http://docs.python.org/library/functions.html?highlight=enumerate#enumerate =noreferrer> 枚举

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