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

基于upstream_costs与planned_expenses字典编写Python单井成本计算函数

修正后的代码实现

原有代码核心问题

  • 6层嵌套循环完全冗余,导致运行耗时极长
  • 列表append方法是原地操作,返回None,赋值给变量会导致变量变为空
  • 引用了未定义的planned_expenses、list_of_operations、numpy等变量,无法正常运行
  • 逻辑结构混乱,while循环无实际作用,返回值语法错误

优化思路

先将upstream_costs转换为操作名到(所属类别、成本)的映射字典,单次遍历即可完成,后续查询操作时间复杂度为O(1),完全避免多层嵌套循环。

完整代码

upstream_costs = {'Drilling':[['Well Casing',0.2],['Cementing',0.1]],
                  'Completion':[['Tubing',0.2],['Packers',0.1],['Frack Fluids',0.1]],
                  'Facilities':[['Separators',0.2],['Dehydrators',0.1]],
                  'Operation':[['Artificial Lift',0.2],['Workover',0.1],['Transportation',0.2]]}

planned_expenses = {'Well-001':['Cementing','Tubing','Packers'],
                    'Well-002':['Tubing','Packers','Separators','Dehydrators'],
                    'Well-003':['Tubing','Frack Fluids','Artificial Lift'],
                    'Well-004':['Separators','Tubing','Frack Fluids','Workover']}

def expense_by_well(upstream_costs, well_name, planned_operations):
    # 提前构建操作映射表,仅需遍历一次
    op_info_map = {}
    for category, op_list in upstream_costs.items():
        for op_name, cost in op_list:
            op_info_map[op_name] = (category, cost)
    
    categories = set()
    total_cost = 0.0
    # 遍历计划作业,统计类别和成本
    for op in planned_operations:
        if op not in op_info_map:
            print(f'操作 {op} 的成本还未定义')
            return None
        cate, cost = op_info_map[op]
        categories.add(cate)
        total_cost += cost
    # 返回结果,保留1位小数避免浮点数精度问题
    return [well_name, categories, round(total_cost, 1)]

# 测试运行
for well_name, ops in planned_expenses.items():
    print(expense_by_well(upstream_costs, well_name, ops))

运行输出

['Well-001', {'Drilling', 'Completion'}, 0.4]
['Well-002', {'Completion', 'Facilities'}, 0.6]
['Well-003', {'Completion', 'Operation'}, 0.5]
['Well-004', {'Completion', 'Facilities', 'Operation'}, 0.6]

和预期输出完全一致。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 15:15:01