gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 17:37:07 26 4
gpt4 key购买 nike

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

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com