【发布时间】:2017-10-04 15:38:40
【问题描述】:
我想跳过 for 循环中的一些语句,以获取 dict 中的最后一个键值对。
让我们假设下一个 sn-p 是真正的程序:
a = { 'a': 1, 'b': 2, 'c': 3 } # I don't know the exact values, so can't test on them
for key, value in a.iteritems():
# statements always to be performed
# statements I want to skip when the current key, value pair is the last unprocessed pair in the dict.
# maybe some more statements not to be skipped (currently not forseen, but might be added in the future)
# other statements in the program
这可能很简单,但我找不到。
好的,我可以使用 while 循环来编写它:
stop = False
b = a.iteritems()
next_key, next_value = b.next()
while True:
key, value = next_key, next_value
# do stuff which should be done always
try:
next_key, next_value = b.next()
except StopIteration:
stop = True
else:
# do stuff which should be done for everything but the last pair
# the future stuff which is not yet forseen.
if stop:
break
但我认为这是丑陋的代码,因此我寻找一种在 for 循环中执行此操作的好方法。 这可能吗?
哦,是的:它需要适用于 python 2.7(而 python 2.5 将是一个奖励),因为这是我工作中的 python 版本(主要是 python 2.7)。
【问题讨论】:
-
字典未排序。您确定要跳过最后一项吗?还是只有一件?
-
最后一个,我的意思是for循环的最后一个,它可能不是最后一个定义的项目(所以它可能是 ('b', 2) 而不是 ('c', 3))。在那一刻,关键和价值不在乎。
-
也许更清楚一点:它应该适用于任何可迭代的
-
恕我直言,您无法使用
for循环使其适用于任何可迭代对象。 -
@MosesKoledoye 和 Jean-Francois Fabre:好吧,不如把它留在字典里,因为这是我现在使用的。
标签: python python-2.7 python-2.5