我有一个嵌套的for循环,我的每个for循环都假定返回一个值,但是最后一个for循环从我的列表中返回5个值。我该怎么做。
ut = [[1,2,3,4,4,5,4,6,6,5,4,3,5], [2,4,6,7,3,4,6,7,4,3], [2,3,4,6,7,3,2,6,7,8,9,5],[2,5,7,4,3,6,7,3,2,5]]
t = [0,1,2,3] #length of ut
n = [12,9,11,9] #length of each list in ut
for ic in t:
for i in n:
for j in n:
print(j)
ii = ut[ic][i] #for example ii = ut[0][12] = 5
jj = ut[ic][j]
我收到此错误
IndexError Traceback (most recent call last)
<ipython-input-45-f5e2a3c2151d> in <module>
6 for j in n:
7 print(j)
----> 8 ii = ut[ic][i] #for example ii = ut[0][12] = 5
9 jj = ut[ic][j]
IndexError: list index out of range
答案 0 :(得分:1)
当ic = 1且i和j等于12时,由于ut中嵌套数组的大小仅为10,因此索引超出范围
答案 1 :(得分:0)
当ic = 1, i = 12, j=12
此刻,uou尝试从ut([2,4,6,7,3,4,6,7,4,3]
)的第二个子列表中获取第12个元素,该元素的长度为10,这说明了异常...
答案 2 :(得分:0)
这是您了解详细信息的代码。
for ic in t:
print(str(t)+"A=>"+str(ic))
for i in ut[ic]:
print(str(ut[ic])+"B=>"+str(i))
if len(ut[ic]) == n[ic]+1:
for j in ut[ic]:
print("C=>"+str(j))
break
这是我的输出:
[0, 1, 2, 3]A=>0
[1, 2, 3, 4, 4, 5, 4, 6, 6, 5, 4, 3, 5]B=>1
C=>1
C=>2
C=>3
C=>4
C=>4
C=>5
C=>4
C=>6
C=>6
C=>5
C=>4
C=>3
C=>5
[0, 1, 2, 3]A=>1
[2, 4, 6, 7, 3, 4, 6, 7, 4, 3]B=>2
C=>2
C=>4
C=>6
C=>7
C=>3
C=>4
C=>6
C=>7
C=>4
C=>3
[0, 1, 2, 3]A=>2
[2, 3, 4, 6, 7, 3, 2, 6, 7, 8, 9, 5]B=>2
C=>2
C=>3
C=>4
C=>6
C=>7
C=>3
C=>2
C=>6
C=>7
C=>8
C=>9
C=>5
[0, 1, 2, 3]A=>3
[2, 5, 7, 4, 3, 6, 7, 3, 2, 5]B=>2
C=>2
C=>5
C=>7
C=>4
C=>3
C=>6
C=>7
C=>3
C=>2
C=>5