python - 收到错误 : list assignment index out of range

标签 python python-2.7 list

我在以下代码中收到超出范围的错误列表分配索引:

n=input("How many numbers?\n")
print "Enter ",n," numbers..."
a=[]
for i in range(0,n):
    a[i]=input()

elem=input("Enter the element to be searched: ")

for i in range(0,n):
    if a[i]==elem:
        flag=1
        break

if flag==1:
    print "Item is present in the list"
else:
    print "Item is not present in the list"

最佳答案

使用 int 添加一些类型安全,使用列表方法 append 和运算符 in:

n = input("How many numbers?\n")
n = int(n)
print "Enter ", n, " numbers..."
a = []
for i in range(n):
    x = input()
    a.append(x)

elem = input("Enter the element to be searched: ")

if elem in a:
    print "Item is present in the list"
else:
    print "Item is not present in the list"

关于python - 收到错误 : list assignment index out of range,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43212994/

相关文章:

python - 如何在 ipython notebook 中为 Hive 查询设置最大分区

python - Psycopg2 --- 插入数组

python - Cron 作业正在将错误写入错误日志,但无法将输出写入输出日志文件

python - 在 python 中创建不可变对象(immutable对象)的修改副本的最快方法

python - 比较列表列表中的 a 并使用 python 添加不同值的最佳方法

python - 保留 python 字典顺序 - (python dict 的延续)

python - 带有自定义选择字段的 Django 模型查询

python : Cost of forming list with comprehension vs standalone function

python - 如何从列表中提取某些项目?

python - 为什么这个 3 行程序返回 None 作为输出?