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

如何将三个Python函数的概率计算结果合并存储为对应三列的表格?

实现方案

1. 改造原有函数,返回计算结果而非直接打印

你当前编写的三个函数仅将结果输出到控制台,没有留存计算值,首先调整函数逻辑将结果存入列表后返回:

def FPP1(x):
    fh_prob = 0.002
    res = []
    for item in x:
        trust = fh_prob if item[0] > 0 else 1 - fh_prob
        res.append(trust)
    return res

def FPP2(x):
    fh_prob = 0.002
    res = []
    for item in x:
        trust = fh_prob if item[1] == 1 else 1 - fh_prob
        res.append(trust)
    return res

def FPP3(x):
    fh_prob = 0.002
    res = []
    for item in x:
        trust = fh_prob if item[2] == 1 else 1 - fh_prob
        res.append(trust)
    return res

2. 合并结果为多列结构

纯Python列表实现

可以通过zip方法将三个结果序列按行合并为嵌套列表,每一行对应三个函数的同位置输出:

col1 = FPP1(x)
col2 = FPP2(x)
col3 = FPP3(x)

# 合并后为512行3列的列表,列顺序为FPP1/FPP2/FPP3
result_table = [list(row) for row in zip(col1, col2, col3)]

Numpy数组实现

如果你需要后续做数值计算,直接生成Numpy二维数组更便捷:

import numpy as np
result_arr = np.column_stack([FPP1(x), FPP2(x), FPP3(x)])

优化建议

三个函数逻辑完全一致,仅判断的列索引不同,你可以写一个通用函数减少重复代码:

def calc_fpp(x, col_idx):
    fh_prob = 0.002
    return [fh_prob if item[col_idx] == 1 else 1 - fh_prob for item in x]

# 调用时传入对应列索引即可
col1 = calc_fpp(x, 0)
col2 = calc_fpp(x, 1)
col3 = calc_fpp(x, 2)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 08:06:01