首页 > 解决方案 > 合并函数的输出

问题描述

我使用以下代码以列表的形式创建了一个二进制“表”:

import numpy as np
from itertools import product

x = [i for i in product(range(2), repeat = 9)]
x = np.array(x)

从那里我创建了 3 个函数来计算我想要的概率:

def FPP1(x):
    fh_prob = 0.002
    trust = 0
    for item in x:
        if item[0] > 0:
            trust = fh_prob
            print(trust)
        if item[0] == 0:
            trust = 1 - fh_prob
            print(trust)

def FPP2(x):
    fh_prob = 0.002
    trust = 0
    for item in x:
        if item[1] == 1:
            trust = fh_prob
            print(trust)
        if item[1] == 0:
            trust = 1 - fh_prob
            print(trust)

def FPP3(x):
    fh_prob = 0.002
    trust = 0
    for item in x:
        if item[2] == 1:
            trust = fh_prob
            print(trust)
        if item[2] == 0:
            trust = 1 - fh_prob
            print(trust)

每个函数大约有 512 个输出,我希望将它们存储在一个列表或表格中。沿着 A 列的线是 FPP1,B 列是 FPP2,第 3 列是 FPP3。我不知道如何做到这一点,任何帮助将不胜感激。

标签: pythonlist

解决方案


不要在函数中打印您需要的值,而是创建一个列表并返回它们。例如,对于FPP1

def FPP1(x):
    fh_prob = 0.002
    trust = 0
    output = [trust] #list that the function will return
    for item in x:
        if item[0] > 0:
            trust = fh_prob
            output.append(trust) #append to the list instead of printing
        if item[0] == 0:
            trust = 1 - fh_prob
            output.append(trust)
    return output #return list of values

FPP2对和进行类似修改后FPP3,您可以使用以下命令创建所有输出的二维列表:

output = [FPP1(x), FPP2(x), FPP3(x)]

如果你想要一个pandas.DataFrame,你可以这样做:

output = pd.DataFrame([FPP1(x), FPP2(x), FPP3(x)]).transpose()
>>> output
         0      1      2
0    0.000  0.000  0.000
1    0.998  0.998  0.998
2    0.998  0.998  0.998
3    0.998  0.998  0.998
4    0.998  0.998  0.998
..     ...    ...    ...
508  0.002  0.002  0.002
509  0.002  0.002  0.002
510  0.002  0.002  0.002
511  0.002  0.002  0.002
512  0.002  0.002  0.002

[513 rows x 3 columns]

推荐阅读