简体   繁体   English

索引超出范围错误:Python

[英]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. 如果我只是简单地将range(40)放进去,错误就会消失。 Any ideas? 有任何想法吗?

i is not an index. i不是指数。 i is the data itself . i就是数据本身 If you wanted to pair up the arrays, just use zip() : 如果要配对数组,只需使用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: 对于需要索引的情况,可以使用enumerate()函数 添加索引:

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: 或者您可以将range()len()以产生一定数量的索引:

for i in range(len(x_data)):

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

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