python - python 错误: name '...' is not defined

标签 python arrays linux

我正在使用列表来存储一些值。

示例代码:

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

但是我收到这样的错误:

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

Python中数组需要初始化吗?我的代码有什么问题?

最佳答案

这是您的代码:

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

有两个问题

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.

所以这是正确的代码:

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

输出: 0 1 2 3

关于python - python 错误: name '...' is not defined,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24360277/

相关文章:

python - 是否可以从参数列表中删除一个项目?

ruby-on-rails - 在 Ruby 中使用 max_by 查找哈希中最大数字的键

python - 对残差平方的numpy数组进行快速迭代

python - 以编程方式获取给定 PID 的子进程列表

linux - 如果任何参数错误如何使 ssh 失败

python - 我如何使用 groupby 来做到这一点?

python - 在numpy中绘制随机元素

python - 显示两个数据框中两列的唯一元素

javascript - 数组切片返回 [object Object] 而不是值

php - 在 Debian 上更新到 PHP 5.4