基本上我想知道在循环迭代中我是否正在处理第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
基本上我想知道在循环迭代中我是否正在处理第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
你觉得使用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
for x in d.keys()[:-1]:
print x
if d: print "last item:", d.keys()[-1]
d = {1:2, 3:4, 5:6, 7:8, 9:0}
时,for x in d[:-1]:
会出现 TypeError: unhashable type
错误,因为字典 d
的值是整数。 - martineaufor x in d.keys()[:-1]
。@Apalala正在遍历d
中的键,而不是d
本身。d
的值为整数在这里是无关紧要的。 - eksortso.keys()
的版本,持续了几分钟。@martineau 可能已经看到了那个版本。 - Apalalad = {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
但是无序字典的最后一项并没有任何意义
list = [1,2,3]
last = list[-1]
for i in list:
if i == last:
print("Last:")
print i
输出:
1
2
Last:
3
警告:仅在最后两个元素不相等时有效
for x in d:
来迭代键,但这些键并不总是以有用的方式排序。 - eksortso