简体   繁体   English

如何多次循环一个随机函数?

[英]How to loop through a random function multiple times?

def a4():
    p = []
    for i in range(10):
        p.append(random.sample(x, 100))
    r = []
    for i in p:
        for j in i:
            r.append(j)
    return r

OUTPUT: OUTPUT:

[0.5202486543583558, 0.5202486543583558, 0.5202486543583558, 0.5202486543583558, 0.5202486543583558]

a1000 = []
for i in range(5):
    a4()
    a1000.append(statistics.mean(a4()))
print(a1000)

I tried to loop through the above defined function using for loop mentioned above but the function only runs once and all the loop results are basically the same. 我尝试使用上面提到的for循环遍历上面定义的函数,但该函数只运行一次,所有循环结果基本相同。 I want the function to run each time through the loop. 我希望每次循环运行该函数。 Could someone tell me why the function is only running once? 有人能告诉我为什么这个功能只运行一次?

As was pointed in the comments the sublists in p in the definition of a4 have exactly the same elements, exactly the same number of times only the order of these element changes. 正如在注释中指出的那样, a4定义中的p中的子列表具有完全相同的元素,完全相同的次数只有这些元素的顺序发生变化。

Therefore the same goes for every new result of a4 . 因此, a4每个新结果都是如此。 These are the same lists upto a permutation of elements. 这些是元素排列的相同列表。 But the order of elements is irrelevant for the computation of the mean (the sum of permuted elements is always the same). 但是元素的顺序与mean的计算无关(置换元素的总和总是相同的)。 Hence you always get the same mean as a result. 因此,你总是得到与结果相同的意思。

However, what you might have wanted to implement is some kind of a bootstrapping mechanism . 但是,您可能想要实现的是某种引导机制 In that case you would want to sample with replacement . 在这种情况下,您会想要替换样品。 And that in turn would yield different result every time. 而这反过来每次都会产生不同的结果。 If this is what you want then replace 如果这是你想要的,那么更换

p.append(random.sample(x, 100))

with

p.append(random.choices(x, k=100))

Also I would consider using numpy for these things. 另外我会考虑使用numpy来做这些事情。 Read about numpy array methods concatenate, flatten. 阅读关于numpy数组方法的连接,展平。 And numpy.random.sample and numpy.random.choice. 和numpy.random.sample和numpy.random.choice。

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

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