gar*_*lfd 5 python for-loop list-comprehension list generator
我需要构建一个生成器,我正在寻找一种方法来缩短这个循环到一行.我尝试枚举但是没有用.
counter=0
for element in string:
if function(element):
counter+=1
yield counter
else:
yield counter
Run Code Online (Sandbox Code Playgroud)
counter=0
for element in string:
counter+=bool(function(element))
yield counter
Run Code Online (Sandbox Code Playgroud)
(是的,加入到布尔整数作品完全一样,如果True是1和False是0).
该bool()电话只有必要的,如果function()能有比其他返回值True,False,1,和0.