在倒数第二次迭代中停止生成器的循环



我有生成器cut_slices,并使用for循环。但我需要对循环外的第一个和last屈服元素做一些具体的工作。使用第一个很简单,只需在循环之前使用next()即可。但是最后怎么办?


fu_a = self.cut_slices(unit, unit_size) #generator (simple for loop with some calculations and yield)
header = self.make_header(p=0, first_byte=unit[0], rtp_type=rtp_type, flag='s')
self.send_packet(header + next(fu_a))
for i in fu_a: #if there is an analogue of a[:-1] for generator object?
header = self.make_header(p=0, first_byte=unit[0], rtp_type=rtp_type,
flag='m')
self.send_packet(header + i)
header = self.make_header(p=0, first_byte=unit[0], rtp_type=rtp_type, flag='e')
self.send_packet(header + next(fu_a))

附言:我知道还有其他方法可以达到同样的结果,只是想弄清楚。

在下面的代码中,在for循环中的aa上运行您想要的函数,并忽略最后一个函数调用。循环结束后,您的变量将为aa

In [1]: a = (i for i in range(10))
In [2]: first = next(a)
In [3]: first
Out[3]: 0
In [4]: for aa in a:
...:     print(aa)
...:
1
2
3
4
5
6
7
8
9
In [5]: aa
Out[5]: 9

在阅读了一篇关于类似主题的媒体文章后,我找到了一种更好的方法来获得最后一个val:

In [29]: def get_last_val(A):
...:     v = next(A)
...:     for a in A:
...:         yield False, v
...:         v = a
...:     yield True, v
In [30]: a = (i for i in range(10))
In [31]: a = get_last_val(a)
In [32]: for aa in a:
...:     print(aa)
...:
(False, 0)
(False, 1) 
(False, 2)
(False, 3)
(False, 4)
(False, 5)
(False, 6)
(False, 7)
(False, 8)
(True, 9)

如果第一个返回值为True,那么这将是迭代中的最后一个值。

如果它不会导致内存问题,只需列出生成器返回的所有内容,并对其进行切片。

fu_a = self.cut_slices(unit, unit_size) #generator (simple for loop with some calculations and yield)
header = self.make_header(p=0, first_byte=unit[0], rtp_type=rtp_type, flag='s')
self.send_packet(header + next(fu_a))
*middle_fu, last_fu = list(fu_a)
for i in middle_fu:
header = self.make_header(p=0, first_byte=unit[0], rtp_type=rtp_type,
flag='m')
self.send_packet(header + i)
header = self.make_header(p=0, first_byte=unit[0], rtp_type=rtp_type, flag='e')
self.send_packet(header + last_fu)

最新更新