简体   繁体   中英

index out of bounds error: Python

In a code I was writing, I keep getting the index error "index out of bounds" however, I don't see a reasonable way that it would give me the error.

Here is where I get this error:

def data_point(box_size): 
    np.random.seed(250)
    x_data = np.random.uniform(-1, 1, 40)*box_size*0.5
    y_data = np.random.uniform(-1, 1, 40)*box_size*0.5
    for i in x_data:
        print "(", x_data[i], ",", y_data[i], ")" 
    return x_data, y_data

This is a part of code that I am using. Whenever I run this I get an error from the fifth line here. If I just simply put range(40) instead the error goes away. Any ideas?

i is not an index. i is the data itself . If you wanted to pair up the arrays, just use zip() :

for x, y in zip(x_data, y_data):
    print "(", x, ",", y, ")" 

For cases where you need an index, you can use the enumerate() function to add an index:

for i, x in enumerate(x_data):
    print "(", x, ",", y_data[i], ")" 

or you can use range() with len() to produce a certain number of indices:

for i in range(len(x_data)):

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