python - 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
解决方案
如果您摆脱所有语法错误,替换a = ["x" * n]
为它应该可以工作。a = ["x"] * n
以下是输出。
[7]
[7, 7]
[7, 7, 1]
[7, 7, 1, 8]
[7, 7, 1, 8, 2]
推荐阅读
- reactjs - 反应集状态部分工作,即使它已更新
- javascript - 触发 PDF 下载 PHP - Laravel 7
- antd - 像完整的日历一样自定义 Antd 日历?
- r - 带有输入文本和输出文本的简单闪亮应用
- c++ - C++ 每天重置雨量计数器
- c# - 从派生类获取基类受保护的属性
- android - React Native 构建失败无法 HEAD /android-jsc/maven-metadata.xml'
- authentication - 如何在 Jmeter 中获取用于登录的 csrf 令牌
- flutter - 如果我不能 100% 确定 Flutter 应用程序的安全性,我应该发布它吗?
- python - UTC 日期时间问题 - 如何适合冒号 - 时间数据“2021-03-11 09:30:01-05:00”与格式“%Y%m%d %H:%M:%S %z”不匹配'