在Python循环中识别当前迭代次数

14 投票
5 回答
23974 浏览
提问于 2025-04-16 10:19

基本上,我想知道在循环的第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 个回答

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

当然可以!请把你想要翻译的内容发给我,我会帮你用简单易懂的语言解释清楚。

6

你觉得用 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
31

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

撰写回答