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

如何将固定3样本的Python代码改写为可扩展的循环列表式函数?

改写为支持任意样本数量的重量计算脚本

以下是改写后的代码,支持先输入样本数量,自动完成所有样本的重量转换与价格计算:

def calculate_specimen_prices():
    unit = "pounds"
    pounds_conversion = 0.00220462  # 重命名变量,含义更清晰

    # 获取样本数量
    specimen_count = int(input("请输入需要处理的样本数量: "))
    specimens = []

    # 循环收集每个样本的重量并完成转换
    for i in range(specimen_count):
        weight = float(input(f"请输入样本 {chr(ord('A') + i)} 的重量: "))
        converted_weight = weight * pounds_conversion
        formatted_weight = "{:.2f}".format(converted_weight)
        specimens.append({
            "name": f"样本 {chr(ord('A') + i)}",
            "converted_weight": converted_weight,
            "formatted_weight": formatted_weight
        })

    # 获取总价格并计算总重量
    total_cost = float(input("请输入这批样本的总价格: "))
    total_weight = sum(specimen["converted_weight"] for specimen in specimens)

    # 计算每个样本的价格并输出结果
    for specimen in specimens:
        individual_price = (specimen["converted_weight"] / total_weight) * (total_cost * 3)
        print(f'{specimen["name"]} 重 {specimen["formatted_weight"]} {unit},价值 ${individual_price:.2f}')

# 执行计算逻辑
calculate_specimen_prices()
input()

关键改动说明:

  • 函数封装逻辑:把所有计算逻辑整合到calculate_specimen_prices函数中,代码更整洁易维护
  • 动态适配样本数量:先询问需处理的样本数,不再局限于固定3个样本
  • 列表存储样本数据:通过循环将每个样本的名称、转换后重量、格式化重量存入列表字典,避免重复定义weightA/converted_weightA这类冗余变量
  • 批量计算与输出:用生成器表达式快速计算总重量,再循环遍历列表输出每个样本结果,消除重复代码
  • 变量名与输出优化:优化变量命名让逻辑更易懂,使用f-string简化字符串拼接,同时给价格保留两位小数,输出更规整

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 07:35:26