简体   繁体   中英

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:

[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. 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.

Therefore the same goes for every new result of 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). 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. Read about numpy array methods concatenate, flatten. And numpy.random.sample and numpy.random.choice.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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