You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何同时对生成器表达式输出的数字流进行求和与计数?

解决方案

可以在单次遍历中同时完成求和与计数,无需存储全量符合条件的元素、无需重复遍历数据流,内存占用为固定的O(1),完全适配大数据量、不可重复遍历流的场景。

基础实现(最直观无额外依赖)

直接手动迭代数据流,同步更新总和与计数两个变量即可,额外添加了除零错误兼容逻辑:

education = '0 1 0 0 0'.split()
salary = [int(s) for s in '50 120 0 40 60'.split()]

total_les = 0
count = 0
# 单次遍历迭代器,即使是不可重复遍历的流也完全适用
for e, s in zip(education, salary):
    if e == '0' and s > 0:
        total_les += s
        count += 1

mean_les = total_les / count if count else 0
print(mean_les) # 输出50.0,对应示例中150/3的计算结果

函数式可选实现

如果偏向无显式循环的写法,可以用functools.reduce实现同等效果:

from functools import reduce

def accumulator(acc, item):
    e, s = item
    if e == '0' and s > 0:
        return (acc[0] + s, acc[1] + 1)
    return acc

total_les, count = reduce(accumulator, zip(education, salary), (0, 0))
mean_les = total_les / count if count else 0

内容的提问来源于stack exchange,提问作者gboffi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 19:06:03