首页 > 解决方案 > For循环中的Python列表索引超出范围

问题描述

请我不知道发生了什么...

import random
o = 0
p = 5
n = 5
z = -1
y = -1
a = ["x" * n]
b = [7,7,1,8,2]

while o != p:
     for x in range(n):
         z += 1
         y += 1
         while a[z] != b[y]
              a[z] = random.randint(0,9)
         y += 1
         print(str(b[0:y])
         y -= 1
         o += 1

我希望一切都可以理解。我的代码有点凌乱并且经过修饰,所以我更改了变量。当第二次打印发生时,错误总是在这里,只有并且总是在第二次打印 b 时,无论 n 是什么,除了 n = 1:

while a[z] != b[y]
IndexError: list index out of range

标签: pythonlistindexing

解决方案


如果您摆脱所有语法错误,替换a = ["x" * n]为它应该可以工作。a = ["x"] * n以下是输出。

[7]
[7, 7]
[7, 7, 1]
[7, 7, 1, 8]
[7, 7, 1, 8, 2]

推荐阅读