python - 尝试在 for 循环中从用户列表中插入值会引发 IndexError

标签 python python-3.x

他/她想要添加多少个值,然后他使用循环插入值。

我使用这个循环进行排序:

value = int(input("how many number u want to add"))

arr = [value]
for n in range(0, value):
    arr[value] = input("Enter value")

for n in range(0, value):
    print(arr[value])

显示错误:

  arr[value] = input("Enter value")
IndexError: list assignment index out of range

最佳答案

如果您认为 arr = [value] 会创建一个长度为 value 的数组,那您就错了,它只是创建了一个只有一个元素的列表,value,如果你想创建一个有value长度的列表,你可以使用列表乘法:

value = int(input("how many number u want to add"))

arr = [0] * value

for n in range(value):
    arr[n] = input("Enter value")

for n in arr:  #  iterate over the elements directly, rather than indexing
    print(n)

另一种方法是使用 list.append 动态添加元素到列表中:

value = int(input("how many number u want to add"))

arr = []

for n in range(value):
    arr.append(input("Enter value"))

for n in arr:
    print(n)

关于python - 尝试在 for 循环中从用户列表中插入值会引发 IndexError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57910736/

相关文章:

python - 如何在 matplotlib 中可视化 95% 的置信区间?

python - 如何在使用 Python 3 的过程中更改数组中的元素?

python - 异步 python : How to call object methods in coroutines?

python - window Python 3.6.4 : Can't find IDLE

python - 为列表预留空间

python - 如何构建一个使用多个属性的基于内容的推荐系统?

python - openCv captureFromCam内存泄漏?

python - 用 scala 阅读 python pickle

python-3.x - 如何将枚举(或列表)传递给SQLite?

python - 如何使用 discord.py 中的 channel ID 设置 channel 对象?