【问题标题】:Running the same function in loop and saving the outputs在循环中运行相同的函数并保存输出
【发布时间】:2022-01-16 02:23:55
【问题描述】:

下面的函数slope() 生成随机的b 值,生成的值用于计算第二个函数中的result。在第一次运行时,slope() 将生成 15 个值并为这 15 个值计算 result 并保存在字典中。我想运行这个函数 100 次,所以对于每组 15 个值,它会为每次运行保存像 output 这样的结果。我也想保存迭代次数。在这里,我尝试将结果保存在字典中,以便稍后将结果保存在 pandas 数据框中。这个函数怎么能运行100次??如何保存结果,以便以后可以轻松地将结果转换为 pandas 数据框?

import numpy as np


# Randomly generated b values 
def slope():
    b = np.random.uniform(1,2.5,15).round(2)
    return b

def psd(a):
    y = np.random.uniform(1,2.5,2).round(2)
    for i in y:
        result = y**(-a) + 1
    dictionary = {f'{a}':f'{list(result.round(5))}'}
    return dictionary

power = list(psd(x) for x in slope())

上述函数的输出是:

[{'2.08': '[1.40189, 1.38618]'}, 
 {'1.19': '[1.41358, 1.35635]'},
 {'2.0': '[1.51757, 1.61035]'},
 {'1.61': '[1.35884, 1.45538]'},
 {'1.07': '[1.38503, 1.80131]'},
 {'1.08': '[1.40485, 1.48885]'},
 {'2.37': '[1.11844, 1.66215]'},
 {'2.45': '[1.14653, 1.20226]'},
 {'1.34': '[1.3748, 1.34766]'},
 {'1.33': '[1.48239, 1.307]'},
 {'2.12': '[1.83302, 1.80152]'},
 {'1.19': '[1.46882, 1.6644]'},
 {'1.65': '[1.35917, 1.2442]'},
 {'1.61': '[1.27493, 1.24591]'},
 {'1.17': '[1.45778, 1.47483]'}]

【问题讨论】:

  • [slope() for _ in range(100)] 开头——这将为您提供调用slope() 100 次的结果列表。
  • 我想我没听清楚你的意思。当我在功率变量中调用您的提及代码并查看时,我看到它给了我 100 个 15 个斜坡的列表。我不是这个意思。生成斜率后它也应该计算结果。
  • 所以[[psd(x) for x in slope()] for _ in range(100)] 可能吗?我仍然不清楚你想要实际生成的是什么,所以我试图提出一些可能让你更接近的建议。
  • 感谢您的提问。我会试试这个。实际上就像我上面提到的,我从slope() 生成了随机的 15 个数字。这 15 个数字用于计算函数 psd() 中定义的公式的结果,然后将结果和斜率保存在字典中。现在这整个过程我想重复 100 次(比如说)。并保存每次重复的结果以及重复次数。
  • @Samwise [[psd(x) for x in slope()] for _ in range(100)] 它完成了工作,但不知道 slope() 值和计算是针对哪个循环的。我还需要保存它为哪个循环进行了计算。

标签: python pandas dataframe function for-loop


【解决方案1】:

这是一个调用 100 次的示例代码。

import numpy as np


# Randomly generated b values 
def slope():
    b = np.random.uniform(1,2.5,15).round(2)
    return b

def psd(a):
    y = np.random.uniform(1,2.5,2).round(2)
    for i in y:
        result = y**(-a) + 1
    dictionary = {f'{a}':f'{list(result.round(5))}'}
    return dictionary


# Save power in a dict with iter value as key.
data = {}
for i in range(100):
    power = list(psd(x) for x in slope())
    data.update({i: power})

# print(data)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-10-05
    • 2022-12-19
    • 1970-01-01
    • 2020-11-09
    • 2019-03-30
    • 2020-08-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多