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

时间:2011-01-20 18:38:23

标签: 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

5 个答案:

答案 0 :(得分:29)

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

答案 1 :(得分:3)

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

答案 2 :(得分:3)

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

答案 3 :(得分:0)

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

但无序词典的最后一项并不意味着什么

答案 4 :(得分:0)

list = [1,2,3]

last = list[-1]

for i in list:
    if i == last:
        print("Last:")
    print i

输出:

1
2
Last:
3