【问题标题】:returning result of a function multiple times within the same function在同一个函数中多次返回函数的结果
【发布时间】:2017-12-06 10:26:25
【问题描述】:

我正在尝试返回一个加起来为 100 .. 11 次的数字列表。

有 3 个数字是从 numpy 随机均匀分布生成的。

我想添加一个 if 语句来查看每个列表的第 1、第 2 和第 3 个数字(总共 11 个).. 如果绘制的 Pearson 相关系数 >0.99。

目前,我只能生成 1 个总和等于 100 的数字列表。

我有以下代码:

import math
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np

c1_high = 98
c1_low = 75
c2_high = 15
c2_low = 6
c3_high = 8
c3_low = 2

def mix_gen():
    while True:
        c1 = np.random.uniform(c1_low, c1_high)
        c2 = np.random.uniform(c2_low, c2_high)
        c3 = np.random.uniform(c3_low, c3_high)
        tot = c1+c2+c3

        if 99.99<= tot <=100.01:
            comp_list = [c1,c2,c3]
            return comp_list

my_list = mix_gen()
print(my_list)

所以如果我要绘制每个组件.. 例如 c1... 我会得到 >0.99 的 R^2 值。

我被困在同一个函数中生成多个列表。我知道这可以在函数之外完成.. 使用 [mix_gen() for _ in range(11)].. 但这不起作用,因为我需要在返回 11 个列表之前对 peasron corr coeff 进行额外检查。

目标:

返回具有以下值的数据框:

   C1    C2    C3    sum
1   70    20    10    100
2   ..
3   ..
4   ..
5   ..
6   ..
7   ..
8   ..
9   ..
10  ..
11  90
R^2  1     1     1

【问题讨论】:

  • 在 if 中使用计数器标志,并且在将 11 个列表附加到容器之前不要从 while 返回
  • 也许你正在寻找yield

标签: python pandas loops numpy pearson-correlation


【解决方案1】:

这可以是一个使用列表列表作为返回的选项

def mix_gen(number):
    flag = 0
    container = []
    while flag < number:
        c1 = np.random.uniform(c1_low, c1_high)
        c2 = np.random.uniform(c2_low, c2_high)
        c3 = np.random.uniform(c3_low, c3_high)
        tot = c1+c2+c3

        if 99.99 <= tot <= 100.01:
            flag += 1
            container.append([c1,c2,c3])

    return container

你用它来称呼它

my_list_of_lists = mix_gen(11)

【讨论】:

  • 是的,确实如此!我现在需要以某种方式检查容器中的 11 个项目,每个组件 C1、C2 和 C3 的 R^2 >0.99 =/.
  • 我可以使用 'container_C1 = [item[0] for item in container]' 来做到这一点。但如果 R​​^2 值 >0.99 未达到,我不确定如何恢复到循环.嗯
  • @Joey 你应该清楚地说明你的目标是什么。我不知道你为什么现在要访问一个不符合你初始要求的 C1 值,因此你一开始没有将它保存在任何容器中。
  • 我已经更新了我的原始帖子以更好地描述我的目标。
  • 这是一个非常有趣的问题要解决......但是,也许仅仅尝试随机数来获得解决方案将需要太多的计算机工作。您应该考虑三个回归线的数学关系来搜索符合两个要求的点集合
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-08-19
  • 1970-01-01
  • 2010-10-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多