简体   繁体   English

python中的错误:名称'...'未定义

[英]Error in python : name '…' is not defined

I am using a list to store some values.我正在使用列表来存储一些值。

Sample code:示例代码:

for i in range(3):
  print i
  lst[i] = i+1
  print lst[i]

But i am getting an error like this:但我收到这样的错误:

lst[i] = i+1
NameError: name 'lst' is not defined

Is it required to initialize an array in python?是否需要在python中初始化数组? What is wrong in my code?我的代码有什么问题?

Here's your code:这是你的代码:

    for i in range(3):
        print i
        lst[i] = i+1
        print lst[i]

there are two things wrong with it它有两个问题

1- you havn't initialize your list, the computer doesn't know yet that you are working with a list (like you do in programs where u keep track of a counter variable like count = count + i because it must have a seed value to start with)
2- you cannot append elements to a list with the assignment operator, use the append function for that.

so here's the correct code:所以这是正确的代码:

    lst = []
    for i in range(3):
        print(i)
        lst.append(i+1)
    print(lst[i])

output : 0 1 2 3输出:0 1 2 3

You should initalise lst as list lst=[]您应该将 lst 初始化为列表lst=[]

lst=[]
for i in range(3):
  print i
  lst.append(i+1)
  print lst[i]

Another way you can do it;另一种方法可以做到; the above 5 lines are equivalent to the following single-line list comprehension, except for the printing:上面5行相当于下面的单行列表理解,除了打印:

lst=[i+1 for i in range(3)]

Yes, you should是的你应该

lst=[]
for i in range(3):
  print i
  lst.append(i+1)
  print lst[i]
lst = []
for i in range(3):
    print i
    lst.append(i+1)
    print lst[i]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM