gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 05:10:07 25 4
gpt4 key购买 nike

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

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com