如何使用两个单独的循环创建嵌套的for循环?

时间:2017-12-02 20:24:15

标签: python loops for-loop

我的任务是运行一个for-loop,它最初在41-65岁生日时找到一个人的投资账户中的资金价值。这是下面的代码。

mu = 0.076 ###Mean
sigma = 0.167 ###Standard deviation
np.exp(np.random.normal(mu, sigma,))


u = .076 ###set variables 
bi = 50000 ###set variables 

empty = [] ###empty list
for i in range(25): ###range for birthdays 40-65
    bi = ((bi) * (np.exp(np.random.normal(mu, sigma))))
    empty.append(bi)
print(empty)
len(empty) ##making sure my lists match up

roundedempty = [ '%.2f' % elem for elem in empty ]
    age = [41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,
                   60,61,62,63,64,65]
    len(age) ##making sure my lists match up
    investing = pd.DataFrame({"Balance":roundedempty, "Age":age})
    investing.set_index('Age', inplace=True)
    investing

When I print this out it give me this: 
Age   Balance           
41    53948.13
.........
65    334294.72

现在我的任务是模拟这100,000次,但我不知道如何在第一组代码中嵌套另一个循环。

mu = 0.076 ###Mean
sigma = 0.167 ###Standard deviation
bi = 50000

lognormvals = np.zeros(100000)
for i in range(100000):
            lognormvals[i] = ((bi) * (np.exp(np.random.normal(mu, sigma,))))
print(lognormvals)
np.mean(lognormvals)

这就是我想要的,但它只是为了他的41岁生日。我的任务是试图从他的41-65岁找到每个生日的手段。如何在第一个循环中嵌套此循环来解决此问题?

My Shot at solving:
def InvestmentSim():
    mu = 0.076 ###Mean
    sigma = 0.167 ###Standard deviation
    np.exp(np.random.normal(mu, sigma,))


    u = .076 ###set variables 
    bi = 50000 ###set variables 

    empty = [] ###empty list
    for i in range(25): ###range for birthdays 40-65
        bi = ((bi) * (np.exp(np.random.normal(mu, sigma))))
        empty.append(bi)

    roundedempty = [ '%.2f' % elem for elem in empty ]
    age = [41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,
                   60,61,62,63,64,65]
    len(age) ##making sure my lists match up
    investing = pd.DataFrame({"Balance":roundedempty, "Age":age})
    investing.set_index('Age', inplace=True)
    a = investing.iloc[24]['Balance']
    return a

def AverageSim(iterations):
    results = []
    for n in range (0, iterations):
        a = InvestmentSim()
        results.append(a)
        print(results)
    return myresult

myresult = AverageSim(1)
myresults = np.array(myresult) # Turn the list of values into an array
mean = np.mean(myresults)
median = np.median(myresults)
print(mean, median)

而不是每年都取得所有的余额而不是在他65岁生日时单独取出余额并将其设置为等于(a)。这是我的代码应该如何工作?似乎没有运行

2 个答案:

答案 0 :(得分:2)

如果你只是想重复第一个片段n次,那么我建议你为你的代码进行模拟,在一个你可以在for循环中重复调用的函数中。该函数应返回您的预期值,for循环应收集结果。循环结束后,您可以使用循环进行进一步的计算,例如mean。

# Your simulation as a callable function
def InvestmentSim():
    # your first code
    return investing


def AverageSims(iterations):

    # Initialise an empty list to collect the results
    results = []

    for n in range (0, iterations):
        investing = InvestmentSim()
        results.append(investing)
        # Adds investing to the end of the list

    # Returns a list of all the dataframes which you can use for future
    # calculations.
    # Or do the desired calculations here and return only those results.
    return results

myresult = AverageSims(100000)

请注意,通过100,000次迭代,您将获得一个非常庞大的数据帧列表。因此,您可能希望进行一些计算或从每次迭代中提取相关结果并丢弃其余部分。例如,您可以保存每个SIM卡的开始和结束余额,并将它们附加到列表并返回它们。 我举一个例子,但我不使用熊猫,所以我不想猜测语法。基本原理是相同的:初始化一些空白列表并将结果附加到for循环中。 如果使用np.array(somelist)

将完成的列表转换为numpy数组,则设置可能会更简单

修改

您的代码未运行,因为您在AverageSims函数中调用了AverageSims函数 ,因此您实际上从未进行过该调用。您需要将该调用移到外部,以便在运行脚本时执行该调用。最简单的方法是以与上面相同的方式编写调用,在任何函数之外并且没有缩进。

此外,如果您的AverageSims()函数没有返回mysresults行,它将返回None。除非您想稍后使用结果,否则这不是问题。 如果您不想保留结果并且乐于像现在一样打印它们,您也可以调用该函数而不将其等同于变量:

def InvestmentSim():
    # your first code
    return investing


def AverageSims(iterations):
    # Repeatedly do the simulation, collect results

    # Returning the results, if you don't need them you can omit this:
    return myresult


# Now call the AverageSims function, otherwise it will never be executed. Note: No indent.  
myresults = AverageSims(100000) # If you're returning the results
# OR:
AverageSims(100000) # If you don't return the results

myresult = np.array(myresult) # Turn the list of values into an array
mean = np.mean(myresult)
median = np.median(myresult)
print(mean, median)

答案 1 :(得分:0)

你可以把一个循环放在另一个循环中:

for x in range(10):
    for y in range(5):
         print(x,y)

我的情况是建议将内循环放入函数中,并在外循环中运行该函数。像这样:

def calculate(*args):
    # do your calculations here that include a loop
    return result

for x in range(100000):
    calculate()