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

如何用Python高效实现Martian-Hopkins查表计算?

解决Martian-Hopkins查表与公式计算问题

1. 用区间规则存储查表数据

不用手动枚举所有数值,直接定义HDL-C和TG的区间范围,对应可调因子。以下是模拟Martian-Hopkins表的核心规则(你可根据实际表调整区间和因子):

# 定义查表规则:每个元素是一个字典,包含HDL-C区间、TG区间、对应可调因子
mh_rules = [
    {"hdl_low": 0, "hdl_high": 40, "tg_low": 0, "tg_high": 199, "factor": 2.0},
    {"hdl_low": 0, "hdl_high": 40, "tg_low": 200, "tg_high": 499, "factor": 5.0},
    {"hdl_low": 41, "hdl_high": 59, "tg_low": 0, "tg_high": 199, "factor": 3.0},
    {"hdl_low": 41, "hdl_high": 59, "tg_low": 200, "tg_high": 499, "factor": 5.3},  # 匹配用户示例的规则
    {"hdl_low": 60, "hdl_high": float('inf'), "tg_low": 0, "tg_high": 199, "factor": 4.0},
    {"hdl_low": 60, "hdl_high": float('inf'), "tg_low": 200, "tg_high": 499, "factor": 6.0},
]

2. 编写区间匹配函数

遍历规则,找到输入HDL-C和TG所属的区间,返回对应的可调因子:

def get_adjustment_factor(hdl_c, tg):
    for rule in mh_rules:
        # 检查HDL-C是否在当前区间内
        hdl_in_range = rule["hdl_low"] <= hdl_c <= rule["hdl_high"]
        # 检查TG是否在当前区间内
        tg_in_range = rule["tg_low"] <= tg <= rule["tg_high"]
        if hdl_in_range and tg_in_range:
            return rule["factor"]
    # 未匹配到区间时抛出异常
    raise ValueError(f"未找到HDL-C={hdl_c}, TG={tg}对应的可调因子")

3. 编写公式计算函数

结合查表结果,计算最终结果:

def calculate_mh_result(tc, hdl_c, tg):
    factor = get_adjustment_factor(hdl_c, tg)
    result = tc - hdl_c - (tg / factor)
    # 保留一位小数,与用户示例结果格式一致
    return round(result, 1)

4. 测试示例

用用户给出的测试值验证功能:

# 示例输入
tc = 332
hdl_c = 55.9
tg = 206

# 计算并输出结果
final_result = calculate_mh_result(tc, hdl_c, tg)
print(f"计算结果:{final_result}")  # 输出:计算结果:237.2

扩展:Pandas版本实现

如果需要批量处理多组数据,可改用Pandas实现,逻辑与纯Python版本一致:

import pandas as pd

# 把规则转成DataFrame
mh_df = pd.DataFrame(mh_rules)

def get_factor_with_pandas(hdl_c, tg):
    # 过滤符合条件的行
    matched = mh_df[(mh_df["hdl_low"] <= hdl_c) & (hdl_c <= mh_df["hdl_high"]) & 
                    (mh_df["tg_low"] <= tg) & (tg <= mh_df["tg_high"])]
    if not matched.empty:
        return matched["factor"].iloc[0]
    raise ValueError("未找到对应的可调因子")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.22 10:54:58