Skip to main content
 首页 » 编程设计

python 3 : perform additional calculation inside a generator

2024年10月24日13www_RR

问题是关于体育节目的。 我从 stdin 得到一个巨大的字符串,如果 char 等于 '.',我必须为每个具有 True 值的 char 创建一个字节数组。否则为 False 值。同时,当我们有两个“.”时,我应该计算案例数量。彼此靠近的符号。

问题 1:是否可以在生成器表达式内执行一些额外的计算以便在使用生成器后可以访问 - 求和、计数、更复杂的计算以避免在创建的列表上进行额外循环?

问题 2:我可以在生成器表达式中访问之前的循环结果吗?我尝试在一个生成器表达式中执行下面的第二个解决方案。

因为这是为了比赛,所以不能使用外部库。

第一个解决方案

res = 0: prev = False 
s = bytearray() 
for c in (c == '.' for c in 'a' + input() + 'a'): 
    res += c and prev 
    prev = c 
    s.append(c) 

第二种解决方案

s = bytearray(c == '.' for c in 'a' + input() + 'a') 
res = sum(map(all,zip(s[1:],s[:-1]))) 

UPD:使用 itertools.tee() 的第三个解决方案 - 不幸的是,这个解决方案比第一个快但比第二个慢

i1,i2,i3 = tee((c == '.' for c in 'a' + input() + 'a'),3) 
next(i1) 
res = sum(a and b for a,b in zip(i1,i2)) 
s = bytearray(i3) 

请您参考如下方法:

Question 1: can be some additional calculation performed inside a generator expression to be accessible after the generator was used - sum, count, more complex calculation to avoid additional looping over the created list?

没有生成器是一次关闭的迭代器,你不能在一次迭代后使用它们。

Question 2: can I access the previous loop result inside a generator expression? I try to perform the second solution below in one generator expression.

因此,如果您想访问生成器表达式中的前一项,您只需在可迭代对象上使用 zip 即可:

inp='a' + input() + 'a' 
(next=='.' and pre== '.' for pre,next in zip(inp,inp[1:]))   

但是如果你想访问生成器的前一项,你可以使用 itertools.tee从您的生成器创建 2 个独立的迭代器并使用 zip 函数创建一个新的生成器(在 python 2 中使用 itertools.izip)包含与上一个和下一个项目的对。

from itertools import tee 
new_generator,MY_generator=tee(MY_generator) 
next(new_generator) 
 
zipped_generator = zip(new_generator,My_generator) 

并在迭代中做:

[for pre,next in zipped_generator]