基本上我想能夠告訴我什麼時候在循環迭代中的第N個項目。 有什麼想法?確定你在python循環中的哪個迭代
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個項目。 有什麼想法?確定你在python循環中的哪個迭代
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
@The MYYN:謝謝。我想我還沒有做任何問題。這就是爲什麼我從未看到複選框大綱。順便提一下,我不明白什麼是複選框大綱。我以後會明白的。 – eyquem 2011-01-20 19:13:28
如何使用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 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 d in d:`遍歷鍵,但這些鍵並不總是以有用的方式排序。 – eksortso 2011-01-20 19:54:58
這裏有一個解決方案,建議去處理第一個項目,而不是最後一個,如果可能的話,並給出一個簡單的方法來檢測。.. http://stackoverflow.com/a/1630350/804616 – trss 2014-07-13 09:51:02