我花了几个小时试图调试这段代码。我想获取列表的倒数第二个元素。
for x, y in itertools.groupby(range(0,10), lambda x: int(x / 3)):
print("the group's key is %d and values are %s" % (x, ','.join(map(str,y))))
temp = itertools.groupby(range(0,10), lambda x: int(x / 3))
the_last_one = None
second_to_last = None
for x,y in temp:
second_to_last = the_last_one
the_last_one = y
print(next(iter(second_to_last)))
为了演示,第一部分的输出是:
the group's key is 0 and values are 0,1,2
the group's key is 1 and values are 3,4,5
the group's key is 2 and values are 6,7,8
the group's key is 3 and values are 9
第二部分的目标是输出倒数第二组中的第一个元素。我期望6
但相反,我得到了异常StopIteration
。如果我将最后一行更改为:
print(next(the_last_one))
然后我得到了预期的结果9
。groupby
也使用与作品输出具有相同结构的元组列表。此代码仅在迭代器上失败。