我想跳过一个for循环的最后关键,在一个字典值对的一些说法。
让我们假设下一个片断是真正的程序:
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版)。
您可以使用itertools.islice
采取除最后所有项目:
from itertools import islice
a = { 'a': 1, 'b': 2, 'c': 3 }
for key, value in islice(a.iteritems(), len(a)-1 if a else None):
...
三元条件,帮助处理情况len(a)-1
给出了否定的结果,即字典是空的。
因为它必须在可迭代的工作,你不能依靠len
。
为了能够使用for
循环,我会创造出延迟yield
直到它知道,如果它是最后一个元素或不是一个辅助发电机的功能。
如果这是最后一个元素,它返回True
+键/值,否则False
+键/值
概念证明:
a = { 'a': 1, 'b': 2, 'c': 3 }
def delayed_iterator(a):
previous_v = None
while True:
v = next(a,None)
if not v:
yield True, previous_v
break
else:
if previous_v:
yield False, previous_v
previous_v = v
for is_last, v in delayed_iterator(iter(a)): # with iter, we make sure that it works with any iterable
print(is_last,v,a[v])
输出是:
False a 1
False b 2
True c 3
有没有一个python字典中的“第一”或“最后”键,因为遍历时,它不保留其元素的插入顺序。
然而,你可以使用一个OrderedDict并承认这样的最后一个元素:
import collections
a = collections.OrderedDict()
a['a'] = 1
a['b'] = 2
a['c'] = 3
for key, value in a.items():
if(key != list(a.items())[-1][0]):
# statements I want to skip when the current key, value pair is the last unprocessed pair in the dict.
首先,普通的字典是没有顺序的,所以你需要使用的元组OrderedDict
或数组来代替。
其次,为什么不排除在收集您遍历最后一个元素。
import collections
a = OrderedDict()
# add stuff to a
for key, value in a.items()[:-1]:
# do something