[英]Loop over 2d array, error TypeError: 'int' object is not subscriptable
I need to loop with y 2d array but it gives me error, it tells me: Traceback (most recent call last): File "plot.py", line 18, in y[k][j] = y[k][j]+1 TypeError: 'int' object is not subscriptable我需要用 y 2d 数组循环,但它给了我错误,它告诉我:回溯(最近一次调用最后一次):文件“plot.py”,第 18 行,在 y[k][j] = y[k][ j]+1 类型错误:'int' 对象不可下标
import matplotlib.pyplot as plt
import math
import numpy as np
jo =[20,30,40,50,60,70]
for k in jo:
x=[]
mo = str(k)
migo = "".join(["./",mo,"/result_no"])
with open(migo) as f:
for line in f:
x.append(float(line))
y = [jo][0]*120
# print(y)
for i in range(len(x)):
j = int(x[i])
y[k][j] = y[k][j]+1
b = [0]*120
for i in range(len(y[k])):
if (k==10):
if (y[k][i]!=0):
b[i] = - math.log( y[k][i] )
if (k!=10):
if (y[k][i]!=0):
b[i] = -math.log( y[k][i] )-0.01*(i-k)*(i-k)
alp = b[:]
for i in range(len(alp)):
if (alp[i]==0):
b.remove(0)
plt.show()
#fy = plt.plot(y)
ft = plt.plot(b)
plt.show()
If you run如果你跑
jo = [20,30,40,50,60,70]
y = [jo][0]*120
print(y)
you will see that y
is a one-dimensional list containing 720 elements, which is 120 * len(jo)
.您将看到
y
是一个包含 720 个元素的一维列表,即120 * len(jo)
。 This is because in the line y = [jo][0]*120
, you create a nested list [[20, 30, 40, 50, 60, 70]]
, then take the first element of that list, which is [20, 30, 40, 50, 60, 70]
(or jo
), and repeat it 120 times.这是因为在
y = [jo][0]*120
,您创建了一个嵌套列表[[20, 30, 40, 50, 60, 70]]
,然后获取该列表的第一个元素,即[20, 30, 40, 50, 60, 70]
(或jo
),并重复 120 次。
Since you are looking for an array of 120 rows, len(jo)
columns, you could create this like:由于您正在寻找一个 120 行、
len(jo)
列的数组,您可以像这样创建:
y = [[0] * len(jo)] * 120
To access the elements according to your code sample, you would modify your for
loop to also get the index of the element in jo
, ie:要根据您的代码示例访问元素,您需要修改
for
循环以获取jo
元素的索引,即:
for idx, k in enumerate(jo):
x=[]
mo = str(k)
migo = "".join(["./",mo,"/result_no"])
with open(migo) as f:
for line in f:
x.append(float(line))
y = [[0] * len(jo)] * 120
# print(y)
for i in range(len(x)):
j = int(x[i])
y[idx][j] = y[idx][j]+1
You may consider whether y
is supposed to be defined inside the for
loop - I suspect not.您可以考虑是否应该在
for
循环中定义y
- 我怀疑不是。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.