0

Create random numbers of 150 and take a uniform sample of 78

import numpy as np

population_data=np.random.randint(1,600,150) # 150 random numbers(integers) genereated 

sample_data=[]
sample_lenth=78

p=30/len(population_data)


for i in range(1,len(population_data)):

    if np.random.random() <=p:
        sample_data.append(population_data[i])
        print(i,len(sample_data))
        if sample_lenth==len(sample_data):
            break;
else: 
    i=10 # (basically wants to change the i value lower that for loop keep running )
    print(i)
        
           
    
print(len(sample_data))
print(sample_data)

for loop is running still 150 which is valid and I cant add more range in for loop as if i>150 then sample_data.append(population_data[i] ) will be out of range.

What I want to achieve is: if sample_lenth==len(sample_data): then break else change the i value to any in between 1-150 that loop continues

Any help !!

Community
  • 1
  • 1
M-shark
  • 25
  • 5
  • 1
    You can use ՛random.sample()՛ to extract a sample from your dataset. – luca.vercelli Mar 29 '20 at 17:44
  • Thanks, @luca.vercelli yes, That can be done, but I am more into break and else operation: else: i=10 # (basically wants to change the value of i, lower than the exact value) print(i) What wrong I am doing here, – M-shark Mar 30 '20 at 18:08

1 Answers1

2

I'm afraid the for...else construct has nothing to do with what you are looking for.

The else clause is executed at most once, after the for loop has finished.

See e.g. https://book.pythontips.com/en/latest/for_-_else.html

You cannot change the i variable inside a for loop. Probably you want to use a while loop. See e.g. How to change index of a for loop?

luca.vercelli
  • 898
  • 7
  • 24