【问题标题】:Stop for loop of generator in second to the last iteration在倒数第二次迭代中停止生成器的循环
【发布时间】:2019-11-07 20:00:35
【问题描述】:

我有 generator cut_slices 并使用 for loop。但是我需要对循环外的第一个和 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))

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

【问题讨论】:

  • 如果你把每个元素放在一个变量中,这样变量总是只有最后一个生成的,当循环结束时,...
  • 您可以跟踪每次迭代的最后一项,因此,在下一次迭代之前,用当前项更新最后一项。
  • 检查 this so question 从 Python 迭代器获取最后一项的最干净方法

标签: python loops generator


【解决方案1】:

在下面的代码中,在 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,那将是迭代中的最后一个值。

【讨论】:

    【解决方案2】:

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

    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)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-10-20
      • 2012-03-05
      • 1970-01-01
      • 2023-03-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多