You need to enable JavaScript to run this app. Python如何仅遍历一次对象列表完成多指标统计避免多次遍历开销
优惠活动
大模型
产品
解决方案
定价
更多

Python如何仅遍历一次对象列表完成多指标统计避免多次遍历开销

from typing import List, Dict
import datetime

def generateReport(structList: List[ResponseStructure]) -> Dict:
    # 处理空列表边界情况
    if not structList:
        raise ValueError("structList不能为空")
    
    # 初始化所有统计变量
    min_lat = float('inf')
    min_lat_date = None
    max_lat = float('-inf')
    max_lat_date = None
    sum_lat = 0.0
    success_count = 0
    error_count = 0
    total = len(structList)

    # 仅遍历一次完成全部统计
    for struct in structList:
        current_lat = struct.latency
        # 更新延迟总和
        sum_lat += current_lat
        # 更新最小延迟
        if current_lat < min_lat:
            min_lat = current_lat
            min_lat_date = struct.date
        # 更新最大延迟
        if current_lat > max_lat:
            max_lat = current_lat
            max_lat_date = struct.date
        # 更新成功请求数
        if struct.isSucceededRequest:
            success_count += 1
        # 更新错误评论数
        if struct.comment == "Error":
            error_count += 1
    
    # 组装结果字典
    return {
        'minLat': (min_lat, min_lat_date.strftime('%m/%d/%Y-%H:%M:%S')),
        'maxLat': (max_lat, max_lat_date.strftime('%m/%d/%Y-%H:%M:%S')),
        'meanLat': sum_lat / total,
        'isSuccessNumber': success_count,
        'numberOfError': error_count
    }

上述实现全程只遍历一次structList,所有统计项都在单次循环内完成更新,相比原来遍历5次的写法,数据量越大时性能优势越明显,同时避免了生成多个中间临时列表,内存占用也更低。如果需要兼容空列表场景,可以把抛错逻辑改成返回默认值即可,比如所有统计项设为0或者None。

内容的提问来源于stack exchange,提问作者Aurélien BOUDIER

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.10 01:30:03