简体   繁体   English

Python3:追加到两个for循环中的列表

[英]Python3: Append to list inside two for loops

I have the following code, that sums up a maximum of 100 random numbers drawn from a normal distribution until it reaches -10 or +10: 我有以下代码,该代码总结了从正态分布中得出的最多100个随机数,直到达到-10或+10:

import numpy as np
mylist=[]
summ = 0
for x in range(100):
    i = np.random.randn()
    summ += i
    mylist.append(i)
    if summ < -10 or summ >10:
        break

Now I want to run this 500 times, and thus create a list with 500 lists, each containing the numbers. 现在,我要运行500次,从而创建一个包含500个列表的列表,每个列表包含数字。 I thought of putting this in another for loop: 我想到将其放在另一个for循环中:

for p in range(500):
    templist = []
    for x in range(100):
        i = np.random.randn()
        summ += i
        templist.append(i)
        if summ < -10 or summ >10:
            mylist.append(templist)
            break

Except that I don't know how to append the element i to the list now... 除了我现在不知道如何将元素i添加到列表中...

Update: I updated the code so the random numbers are first added to a temporary list templist , and as soon as the sum walks out the limits, it appends this list to mylist . 更新:我更新的代码,这样的随机数首先加入到临时列表templist ,并尽快总和走出限制,其追加此列表mylist However, not working still! 但是,仍然无法正常工作!

mylist = []
for p in range(500):
    new_list = []
    summ = 0
    for x in range(100):
        i = np.random.randn()
        summ += i
        new_list.append(i)
        if summ < -10 or summ >10:
            break
    mylist.append(new_list)

You can execute any function 500 times and save the result in a list by using decorators. 您可以执行500次任何功能,并使用装饰器将结果保存在列表中。 Just put your functionality inside a function: 只需将您的功能放在一个函数中:

import numpy as np

def execute_500_times(func):

    def multiplying_func(*args, **kwargs):
        list_of_results = list()
        for _ in range(500):
            list_of_results.append(func(*args, **kwargs))
        return list_of_results

    return multiplying_func

@execute_500_times
def myfunc():
    mylist=list()
    summ = 0
    for x in range(100):
        i = np.random.randn()
        summ += i
        mylist.append(i)
        if summ < -10 or summ >10:
            break

    return mylist

result = myfunc()

An advantage of this is that the decorator function can be reused for other functions as well instead of just modifying your original function. 这样的一个优点是装饰器函数也可以重用于其他函数,而不仅仅是修改原始函数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM