You need to enable JavaScript to run this app. Python 订阅费用统计:如何实现全账户计算结果合并
优惠活动
大模型
产品
解决方案
定价
更多

Python 订阅费用统计:如何实现全账户计算结果合并

全量账户费用合并统计的调整方案

当前代码无法实现合并统计的核心原因是:subscription_summary函数仅在内部完成费用计算和单账户打印,没有将计算出的费用值对外返回,外层循环遍历账户时无法获取每个账户的分项金额,自然没法做跨账户的累加汇总。
调整操作分为两部分:

  • 保留原有单账户核算、打印的全部逻辑,新增函数返回值,将计算得到的三类分项费用、账户总费用传出给外层程序
  • 在主程序中初始化全局累加变量,每遍历处理一个账户就同步累加对应费用,所有账户遍历完成后,统一输出全量合并的统计结果

调整后的完整可运行代码

#!/bin/python3

sub_fee = 7 
ad_fee = 2 
vod_fee = 27.99 

def subscription_summary(months_subscribed, ad_free_months, video_on_demand_purchases, account_number):
    # 原有单账户费用计算逻辑完全保留
    total_sub_fee = sub_fee * months_subscribed
    total_ad_fee = ad_fee * ad_free_months
    total_vod_fee = vod_fee * video_on_demand_purchases
    account_total = total_sub_fee + total_ad_fee + total_vod_fee

    # 原有单账户明细打印逻辑完全保留
    print(f"Account {account_number} made ${account_total:,.2f} total")
    print(f">>>  ${total_sub_fee:,.2f} from monthly subscription fees")
    print(f">>>  ${total_ad_fee:,.2f} from Ad-free upgrades")
    print(f">>>  ${total_vod_fee:,.2f} from Video on Demand purchases")
    print() 

    # 新增:将核算结果返回,供外层累加使用
    return total_sub_fee, total_ad_fee, total_vod_fee, account_total

if __name__ == '__main__':
    print("Output")
    print()

    # 初始化全量统计的累加容器
    aggregate_sub_fee = 0.0
    aggregate_ad_fee = 0.0
    aggregate_vod_fee = 0.0
    grand_total = 0.0

    sub_lists = [[1,1,3],[2,0,0],[2,2,1]]
    for index in range(len(sub_lists)):
        account_number = index + 1
        account_data = sub_lists[index]
        # 接收单账户核算结果,同步累加到全局统计变量
        a_sub, a_ad, a_vod, a_total = subscription_summary(
            account_data[0], account_data[1], account_data[2], account_number
        )
        aggregate_sub_fee += a_sub
        aggregate_ad_fee += a_ad
        aggregate_vod_fee += a_vod
        grand_total += a_total

    # 所有账户遍历完成后,打印合并汇总结果
    print("===== Combined Cross-Account Summary =====")
    print(f"Total revenue across all accounts: ${grand_total:,.2f}")
    print(f">>>  ${aggregate_sub_fee:,.2f} from aggregated monthly subscription fees")
    print(f">>>  ${aggregate_ad_fee:,.2f} from aggregated Ad-free upgrades")
    print(f">>>  ${aggregate_vod_fee:,.2f} from aggregated Video on Demand purchases")

运行效果说明

逐账户的明细打印逻辑和原代码完全一致,所有单账户明细输出完成后,会自动在末尾输出跨账户的合并统计块:基于示例中的3个账户数据,最终合并汇总的总金额为152.96美元,其中月度订阅费合计35.00美元、免广告升级费合计6.00美元、视频点播费合计111.96美元,和手动核算的结果完全一致。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.11.19 12:24:09