【问题标题】:Getting an error: list assignment index out of range出现错误:列表分配索引超出范围
【发布时间】:2017-04-05 01:34:36
【问题描述】:

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

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"

【问题讨论】:

  • 使用a.append(),而不是a[i] =
  • 请发布堆栈跟踪。 Python 非常好,可以为您提供有关错误的详细信息……请先付款!

标签: python python-2.7 list


【解决方案1】:

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"

【讨论】:

    【解决方案2】:

    您正在设置列表索引而没有声明。见:

    a=[]
    

    然后你想访问一些索引?你正在读取一个带有输入的字符串,在使用之前将其转换。事情看起来像:

    n = int(n)
    a= []*n
    

    【讨论】:

      【解决方案3】:

      这样使用,

      n=input("How many numbers?\n")
      print "Enter ",n," numbers..."
      # assigning with n times zero values which will get overwritten when you input values.
      a=[0]*n
      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"
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-09-06
        • 2019-07-26
        • 1970-01-01
        • 2017-06-28
        • 1970-01-01
        • 2017-10-30
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多