我使用列表来存储一些值。
示例代码:
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中初始化数组?我的代码出了什么问题?
答案 0 :(得分:2)
你应该将lst列为lst=[]
lst=[]
for i in range(3):
print i
lst.append(i+1)
print lst[i]
你可以做到的另一种方式;以上5行相当于以下单行列表理解,但打印除外:
lst=[i+1 for i in range(3)]
答案 1 :(得分:2)
这是您的代码:
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
答案 2 :(得分:1)
是的,你应该
lst=[]
for i in range(3):
print i
lst.append(i+1)
print lst[i]
答案 3 :(得分:0)
lst = [] for i in range(3): print i lst.append(i+1) print lst